### Build Twilio Java Library from Source with Maven Source: https://github.com/twilio/twilio-java/blob/main/README.md Instructions for cloning the `twilio-java` repository and building it locally using Maven. This process requires Maven to be installed and will compile the source code and install it into your local Maven repository. ```Shell git clone git@github.com:twilio/twilio-java cd twilio-java mvn install # Requires maven, download from https://maven.apache.org/download.html ``` -------------------------------- ### Initializing Twilio Client (7.x) Source: https://github.com/twilio/twilio-java/wiki/Java-Version-7.x-Usage-Guide Illustrates how to initialize the Twilio client in `twilio-java` 7.x using the account SID and auth token. This initialization is a prerequisite for making any API calls with the library. ```java Twilio.init(ACCOUNT_SID, AUTH_TOKEN); ``` -------------------------------- ### Importing Twilio Client (7.x) Source: https://github.com/twilio/twilio-java/wiki/Java-Version-7.x-Usage-Guide Shows the simplified import statement for the `twilio-java` 7.x library, where all functionality is consolidated under a single `Twilio` class, streamlining client access. ```java import com.twilio.Twilio; ``` -------------------------------- ### Fetching a Twilio Resource (7.x) Source: https://github.com/twilio/twilio-java/wiki/Java-Version-7.x-Usage-Guide Demonstrates how to retrieve an existing Twilio resource, such as a Message, using the `Fetcher` action. It shows fetching by SID and then accessing a property of the fetched resource. ```java Message message = Message.fetcher(ACCOUNT_SID, "SM123").fetch(); System.out.println("message sid: " + message.getSid()); // message sid: SM123 ``` -------------------------------- ### Initialize Twilio Java Client with Basic Authentication Source: https://github.com/twilio/twilio-java/blob/main/README.md Demonstrates the standard way to initialize the Twilio Java client using your Account SID and Auth Token. This setup is required for most API interactions that use basic authentication. ```java import com.twilio.Twilio; import com.twilio.exception.AuthenticationException; public class Example { private static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; private static final String AUTH_TOKEN = "your_auth_token"; public static void main(String[] args) throws AuthenticationException { Twilio.init(ACCOUNT_SID, AUTH_TOKEN); } } ``` -------------------------------- ### Importing Twilio Clients (Prior 7.x) Source: https://github.com/twilio/twilio-java/wiki/Java-Version-7.x-Usage-Guide Demonstrates how Twilio clients were imported in versions of `twilio-java` prior to 7.x, showing separate imports for different services like Lookups, IP Messaging, and a generic REST client. ```java import com.twilio.sdk.LookupsClient; import com.twilio.sdk.TwilioIPMessagingClient; import com.twilio.sdk.TwilioRestClient; ``` -------------------------------- ### Listing Twilio Resources with Reader (7.x) Source: https://github.com/twilio/twilio-java/wiki/Java-Version-7.x-Usage-Guide Demonstrates how to retrieve a list of Twilio resources, such as Messages, using the `Reader` action. It iterates over the results, highlighting that the library handles paging automatically. ```java Iterable messages = Message.reader(ACCOUNT_SID).read(); for (Message message : messages) { System.out.println("message sid: " + message.getSid()); // message sid: SMxxx } ``` -------------------------------- ### Authenticate with Twilio using Bearer Tokens in Java Source: https://github.com/twilio/twilio-java/blob/main/examples/BearerTokenAuthentication.md This example demonstrates how to initialize Twilio's organization token authentication using client credentials and then fetch account details. It shows two methods for obtaining an access token: using the default `init` method or providing a custom token manager implementation. The `fetchAccountDetails` method illustrates how to read account information after successful authentication. ```Java 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); } } ``` -------------------------------- ### Creating a Twilio Resource (7.x) Source: https://github.com/twilio/twilio-java/wiki/Java-Version-7.x-Usage-Guide Illustrates how to create a new Twilio resource, like sending a Message, using the `Creator` action. It includes specifying recipient, sender, and message body as parameters. ```java Message message = Message.creator( ACCOUNT_SID, new PhoneNumber("+15558881234"), new PhoneNumber("+15558884321"), "Hello world!" ).create(); System.out.println("message body: " + message.getBody()); // message body: Hello world! ``` -------------------------------- ### CallUpdater Builder Methods (7.x) Source: https://github.com/twilio/twilio-java/wiki/Java-Version-7.x-Usage-Guide Illustrates the builder pattern used in `twilio-java` 7.x, specifically showing a list of setter methods available on the `CallUpdater` class for configuring various call properties like URL, method, and status. ```java public CallUpdater setUrl(final URI url) public CallUpdater setUrl(final String url) public CallUpdater setMethod(final HttpMethod method) public CallUpdater setStatus(final Call.Status status) public CallUpdater setFallbackUrl(final URI fallbackUrl) public CallUpdater setFallbackUrl(final String fallbackUrl) public CallUpdater setFallbackMethod(final HttpMethod fallbackMethod) public CallUpdater setStatusCallback(final URI statusCallback) public CallUpdater setStatusCallback(final String statusCallback) public CallUpdater setStatusCallbackMethod(final HttpMethod statusCallbackMethod) ``` -------------------------------- ### Updating a Twilio Resource (7.x) Source: https://github.com/twilio/twilio-java/wiki/Java-Version-7.x-Usage-Guide Shows how to modify an existing Twilio resource using the `Updater` action. It demonstrates creating a message, then updating its body, and printing both the original and updated values. ```java Message message = Message.creator( ACCOUNT_SID, new PhoneNumber("+15558881234"), new PhoneNumber("+15558884321"), "Hello world!" ).create(); System.out.println("message sid: " + message.getSid()); // message sid: SM123 System.out.println("message body: " + message.getBody()); // message body: Hello world! Message updatedMessage = Message.updater(ACCOUNT_SID, message.getSid()) .setBody("Updated body!") .update(); System.out.println("message sid: " + message.getSid()); // message sid: SM123 System.out.println("message body: " + message.getBody()); // message body: Updated body! ``` -------------------------------- ### Send SMS Message using Twilio Java SDK Source: https://github.com/twilio/twilio-java/blob/main/README.md A complete Java example demonstrating how to initialize the Twilio client and send an SMS message using the `Message.creator` method. It highlights the use of `ACCOUNT_SID`, `AUTH_TOKEN`, and `PhoneNumber` objects for message construction. ```Java import com.twilio.Twilio; import com.twilio.rest.api.v2010.account.Message; import com.twilio.type.PhoneNumber; public class Example { // Find your Account Sid and Token at console.twilio.com public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; public static final String AUTH_TOKEN = "your_auth_token"; public static void main(String[] args) { Twilio.init(ACCOUNT_SID, AUTH_TOKEN); Message message = Message .creator( new PhoneNumber("+15558675309"), new PhoneNumber("+15017250604"), "This is the ship that made the Kessel Run in fourteen parsecs?" ) .create(); System.out.println(message.getSid()); } } ``` -------------------------------- ### Configuring Custom HTTP Client (7.x) Source: https://github.com/twilio/twilio-java/wiki/Java-Version-7.x-Usage-Guide Shows how to inject a custom HTTP client into the `twilio-java` 7.x library. This allows developers to use their preferred HTTP client implementation for advanced network configuration and control. ```java Twilio.setRestClient(new CustomRestClient()); ``` -------------------------------- ### Handle Asynchronous Twilio API Requests in Java Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md This example illustrates the change in handling asynchronous API requests within the Twilio Java Helper Library. In version 7.x.x, `ListenableFuture` from Guava was used for asynchronous operations, whereas version 8.x.x adopted `CompletableFuture` from standard Java concurrency, reflecting the library's move away from Guava dependencies. ```Java // 7.x.x import com.twilio.rest.api.v2010.account.IncomingPhoneNumber; import com.twilio.type.PhoneNumber; import com.google.common.util.concurrent.ListenableFuture; ListenableFuture incomingPhoneNumber = IncomingPhoneNumber.creator(new PhoneNumber("+11234567890")).createAsync(); ``` ```Java // 8.x.x import com.twilio.rest.api.v2010.account.IncomingPhoneNumber; import com.twilio.type.PhoneNumber; import java.util.concurrent.CompletableFuture; CompletableFuture incomingPhoneNumber = IncomingPhoneNumber.creator(new PhoneNumber("+11234567890")).createAsync(); ``` -------------------------------- ### Update Twilio Java TwiML Task Body Parameter Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md This example demonstrates the change in the `Task` TwiML resource in Twilio Java SDK 7.17.x. The `data` parameter has been renamed to `body` and is now a required constructor argument, streamlining the creation of `Task` objects. ```java // 7.16.x Task t = new Task.Builder().data("body").build(); ``` ```java // 7.17.x new Task.Builder("body").build() ``` -------------------------------- ### Standardize TwiML Class Construction to Builder Pattern in Twilio Java Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md Twilio TwiML classes can no longer be directly instantiated. All TwiML resource construction now consistently uses the Builder pattern, ensuring a uniform approach to object creation across the SDK. ```java // 7.16.x Hangup hangup = new Hangup(); Body body = new Body("This body!"); ``` ```java // 7.17.x Hangup hangup = new Hangup.Builder().build(); Body body = new Body.Builder("This body!").build(); ``` -------------------------------- ### Example TwiML XML Output for Voice Response Source: https://github.com/twilio/twilio-java/blob/main/README.md This XML snippet represents the TwiML output generated by the corresponding Java builder code. It defines a voice response that includes a `` verb for text-to-speech and a `` verb to play an audio file in a loop. This is the standard XML format Twilio expects to control call flow and interactions. ```xml Hello World! https://api.twilio.com/cowbell.mp3 ``` -------------------------------- ### Fetch Twilio Message using OAuth in Java Source: https://github.com/twilio/twilio-java/blob/main/examples/FetchMessageUsingOAuth.md This Java example demonstrates how to initialize the Twilio client using OAuth client credentials (`ClientCredentialProvider`) and then fetch a specific message resource by its SID. It shows both options for `Twilio.init`: with and without an explicit `accountSid` parameter. ```Java 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(); } } ``` -------------------------------- ### Twilio Java SDK TwiML Method Renaming Reference Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md This API documentation details the specific method renames within the Twilio Java SDK's TwiML classes, where method names now align with the nested TwiML element's verb/noun. ```APIDOC com.twilio.twiml.voice.Refer: - referSip(ReferSip referSip) -> sip(ReferSip referSip) com.twilio.twiml.voice.Say: - ssmlBreak(SsmlBreak ssmlBreak) -> break_(SsmlBreak ssmlBreak) - ssmlEmphasis(SsmlEmphasis ssmlEmphasis) -> emphasis(SsmlEmphasis ssmlEmphasis) - ssmlLang(SsmlLang ssmlLang) -> lang(SsmlLang ssmlLang) - ssmlP(SsmlP ssmlP) -> p(SsmlP ssmlP) - ssmlPhoneme(SsmlPhoneme ssmlPhoneme) -> phoneme(SsmlPhoneme ssmlPhoneme) - ssmlProsody(SsmlProsody ssmlProsody) -> prosody(SsmlProsody ssmlProsody) - ssmlS(SsmlS ssmlS) -> s(SsmlS ssmlS) - ssmlSayAs(SsmlSayAs ssmlSayAs) -> sayAs(SsmlSayAs ssmlSayAs) - ssmlSub(SsmlSub ssmlSub) -> sub(SsmlSub ssmlSub) - ssmlW(SsmlW ssmlW) -> w(SsmlW ssmlW) ``` -------------------------------- ### Twilio Serverless API Build Enhancements Source: https://github.com/twilio/twilio-java/blob/main/CHANGES.md Updates to the Twilio Serverless API, adding a `runtime` field to the Build response and as an optional parameter for the Build create endpoint. Also includes the addition of `@twilio/runtime-handler` dependency to the Build response example. ```APIDOC Serverless Build API: - Add runtime field to Build response and as an optional parameter to the Build create endpoint. - Add @twilio/runtime-handler dependency to Build response example. ``` -------------------------------- ### Migrating Recording Fetcher/Reader Class in Twilio Java SDK Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md This snippet demonstrates the change in class name for accessing `Recording` fetcher and reader methods between Twilio Java SDK versions 7.10.x and 7.11.x. The `Recording` class was renamed to `RoomRecording` to better reflect its context. ```java // 7.10.x Recording.fetcher(); Recording.reader(); ``` ```java // 7.11.x RoomRecording.fetcher(); RoomRecording.reader(); ``` -------------------------------- ### Migrate Twilio Java SDK IceServer URL Types from URI to String Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md This change updates the data types for `url` and `urls` properties within the `com.twilio.type.IceServer` class. They have been changed from `java.net.URI` to `String`. ```Java // 7.x.x import com.twilio.rest.api.v2010.account.Token; import com.twilio.type.IceServer; import java.net.URI; Token token = Token.creator().create(); for (IceServer iceServer : token.getIceServers()) { URI url = iceServer.getUrl(); URI urls = iceServer.getUrls(); } ``` ```Java // 8.x.x import com.twilio.rest.api.v2010.account.Token; import com.twilio.type.IceServer; Token token = Token.creator().create(); for (IceServer iceServer : token.getIceServers()) { String url = iceServer.getUrl(); String urls = iceServer.getUrls(); } ``` -------------------------------- ### Refactor Twilio Java SDK TwiML Builder Methods for Nested Elements Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md This snippet illustrates the renaming convention for TwiML builder methods. Method names now directly match the nested element's TwiML verb/noun, improving consistency and readability. ```Java // 7.x.x import com.twilio.twiml.voice.Refer; import com.twilio.twiml.voice.ReferSip; ReferSip sip = new ReferSip.Builder("sip:alice@example.com").build(); Refer refer = new Refer.Builder().referSip(sip).build(); ``` ```Java // 8.x.x import com.twilio.twiml.voice.Refer; import com.twilio.twiml.voice.ReferSip; ReferSip sip = new ReferSip.Builder("sip:alice@example.com").build(); Refer refer = new Refer.Builder().sip(sip).build(); ``` -------------------------------- ### Sending SMS with a Custom TwilioRestClient for Proxy Source: https://github.com/twilio/twilio-java/blob/main/advanced-examples/custom-http-client.md This example demonstrates how to send an SMS message using a custom `TwilioRestClient` configured to work with a proxy server. It initializes Twilio, loads environment variables for credentials and proxy details, then creates and sets a custom `TwilioRestClient` before sending the message. This approach allows modifying HTTP requests, such as for proxy authentication. ```java // Install the Java helper library from twilio.com/docs/java/install import com.twilio.Twilio; import com.twilio.http.TwilioRestClient; import com.twilio.rest.api.v2010.account.Message; import com.twilio.type.PhoneNumber; import io.github.cdimascio.dotenv.Dotenv; public class Example { public static void main(String args[]) { Dotenv dotenv = Dotenv.configure().directory(".").load(); String ACCOUNT_SID = dotenv.get("ACCOUNT_SID"); String AUTH_TOKEN = dotenv.get("AUTH_TOKEN"); String PROXY_HOST = dotenv.get("PROXY_HOST"); int PROXY_PORT = Integer.parseInt(dotenv.get("PROXY_PORT")); Twilio.init(ACCOUNT_SID, AUTH_TOKEN); ProxiedTwilioClientCreator clientCreator = new ProxiedTwilioClientCreator( ACCOUNT_SID, AUTH_TOKEN, PROXY_HOST, PROXY_PORT ); TwilioRestClient twilioRestClient = clientCreator.getClient(); Twilio.setRestClient(twilioRestClient); Message message = Message .creator( new PhoneNumber("+15558675310"), new PhoneNumber("+15017122661"), "Hey there!" ) .create(); System.out.println(message.getSid()); } } ``` -------------------------------- ### Merge EnqueueTask functionality into Enqueue TwiML in Twilio Java Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md The `EnqueueTask` TwiML resource has been removed and its functionality merged directly into the `Enqueue` resource. This change simplifies the API by allowing `Task` TwiML resources to be nested directly within `Enqueue` using a `task` builder method, eliminating the need for a separate `EnqueueTask` class. ```java // 7.16.x EnqueueTask enqueue = new EnqueueTask.Builder(new Task.Builder().build()).build() ``` ```java // 7.17.x Enqueue enqueue = new Enqueue.Builder() .task(new Task.Builder().build()) .build() ``` -------------------------------- ### Update Twilio Java TwiML Redirect URL Parameter Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md This snippet demonstrates the change in the Twilio Java SDK's TwiML `Redirect` resource. In version 7.17.x, the `url` parameter is now a required constructor argument, simplifying its instantiation compared to the builder pattern used in 7.16.x. ```java // 7.16.x Redirect redirect = new Redirect.Builder().url("http://example.com").build(); ``` ```java // 7.17.x Redirect redirect = new Redirect.Builder("https://example.com").build(); ``` -------------------------------- ### Old Twilio Java TwiML Arbitrary Attribute Setting Source: https://github.com/twilio/twilio-java/wiki/Java-Version-7.x-Benefits This example illustrates how older `twilio-java` versions allowed setting arbitrary attributes on TwiML elements using a generic `set` method, even if those attributes were not supported by the TwiML resource. This could lead to the generation of invalid TwiML. ```Java Say say = new Say(); say.set("foo", "bar"); ``` -------------------------------- ### Update Twilio Java SDK Date Properties to java.time.ZonedDateTime Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md This change affects the type used for getting and setting date-related properties across all resources. Previously, `org.joda.time.DateTime` was used, but now `java.time.ZonedDateTime` is the standard. ```Java // 7.x.x import com.twilio.rest.api.v2010.account.IncomingPhoneNumber; import com.twilio.type.PhoneNumber; import org.joda.time.DateTime; IncomingPhoneNumber incomingPhoneNumber = IncomingPhoneNumber.fetcher("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch(); DateTime dateCreated = incomingPhoneNumber.getDateCreated(); ``` ```Java // 8.x.x import com.twilio.rest.api.v2010.account.IncomingPhoneNumber; import com.twilio.type.PhoneNumber; import java.time.ZonedDateTime; IncomingPhoneNumber incomingPhoneNumber = IncomingPhoneNumber.fetcher("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch(); ZonedDateTime dateCreated = incomingPhoneNumber.getDateCreated(); ``` -------------------------------- ### Rename ConferenceEvent Enum to Event in Twilio Java TwiML Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md This example illustrates the renaming of the `ConferenceEvent` enum within the `Conference` TwiML resource in Twilio Java SDK version 7.17.x. The enum is now directly nested as `Conference.Event`, standardizing its location within the resource. ```java // 7.16.x Conference conference = new Conference.Builder("my conference") .statusCallbackEvents(Lists.newArrayList(Conference.ConferenceEvent.END, Conference.ConferenceEvent.JOIN)) .build(); ``` ```java // 7.17.x Conference conference = new Conference.Builder("my conference") .statusCallbackEvents(Lists.newArrayList(Conference.Event.END, Conference.Event.JOIN)) .build(); ``` -------------------------------- ### Old Twilio Java Invalid Action Example (PhoneNumber Update) Source: https://github.com/twilio/twilio-java/wiki/Java-Version-7.x-Benefits This snippet shows an action that was syntactically allowed in older `twilio-java` versions but would result in a runtime exception because updating a `PhoneNumber` is not supported by the Twilio API. This highlights the lack of compile-time validation for supported resource actions in previous library versions. ```Java LookupsClient lc = new LookupsClient(ACCOUNT_SID, AUTH_TOKEN); PhoneNumber number = lc.getPhoneNumber("+18089263410"); number.update(new HashMap()); ``` -------------------------------- ### Make an Outbound Call using Twilio Java SDK Source: https://github.com/twilio/twilio-java/blob/main/README.md Shows how to programmatically initiate an outbound call using the Twilio Java SDK. It demonstrates creating a Call resource by specifying 'from' and 'to' phone numbers and a TwiML URI for call instructions. ```java import com.twilio.Twilio; import com.twilio.rest.api.v2010.account.Call; import com.twilio.type.PhoneNumber; import java.net.URI; import java.net.URISyntaxException; public class Example { public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; public static final String AUTH_TOKEN = "your_auth_token"; public static void main(String[] args) throws URISyntaxException { Twilio.init(ACCOUNT_SID, AUTH_TOKEN); Call call = Call .creator( new PhoneNumber("+14155551212"), new PhoneNumber("+15017250604"), new URI("http://demo.twilio.com/docs/voice.xml") ) .create(); System.out.println(call.getSid()); } } ``` -------------------------------- ### Advanced Twilio Java Client Initialization Options Source: https://github.com/twilio/twilio-java/blob/main/README.md Describes alternative client initialization methods for the Twilio Java SDK, including the TwilioNoAuth client for endpoints without basic authentication, custom token managers for dynamic token generation, and notes on OAuth 2.0 support (currently in beta). ```APIDOC Advanced Twilio Java Client Initialization: 1. Client without Basic Authentication: - Use: TwilioNoAuth client - Purpose: For endpoints that do not require basic authentication. 2. Custom Token Manager: - Interface: Implement com.twilio.security.token.Token - Purpose: To bypass standard initialization and provide custom token generation logic, e.g., calling an external token endpoint. 3. OAuth 2.0 Client Credentials Flow: - Status: Currently in beta. - Purpose: For authentication using bearer tokens, as seen in Organization domain endpoints. - Note: Implementation is subject to change. ``` -------------------------------- ### Configure SLF4J Debug Logging for Twilio HTTP Client with Log4j2 Source: https://github.com/twilio/twilio-java/blob/main/README.md This XML configuration snippet for Log4j2 demonstrates how to enable debug logging specifically for the Twilio HTTP client (`com.twilio.http`). It directs these debug messages to the console while maintaining a default info level for other application logs. This setup requires `log4j-slf4j-impl`, `log4j-core`, and `log4j-api` dependencies in your project. ```xml ``` -------------------------------- ### Generate TwiML Voice Response using Twilio Java Builder Source: https://github.com/twilio/twilio-java/blob/main/README.md This Java code showcases the builder pattern for constructing TwiML (Twilio Markup Language) voice responses. It creates a `VoiceResponse` that first uses text-to-speech to say 'Hello World!' and then plays an MP3 file from a URL five times. This approach simplifies the programmatic generation of complex TwiML for interactive voice applications. ```java TwiML twiml = new VoiceResponse.Builder() .say(new Say.Builder("Hello World!").build()) .play(new Play.Builder("https://api.twilio.com/cowbell.mp3").loop(5).build()) .build(); ``` -------------------------------- ### Package Twilio Java JAR File with Maven Source: https://github.com/twilio/twilio-java/blob/main/README.md Command to build a `.jar` file for the `twilio-java` library using Maven's `package` goal. This will compile the project and create a distributable JAR file in the `target` directory. ```Shell mvn package ``` -------------------------------- ### Twilio and Proxy Configuration Environment Variables Source: https://github.com/twilio/twilio-java/blob/main/advanced-examples/custom-http-client.md This snippet illustrates the structure of a `.env` file used to store sensitive credentials and proxy settings for the application. It includes placeholders for the Twilio Account SID, Auth Token, proxy host, and proxy port, which are loaded at program startup to configure the Twilio client. ```env ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx AUTH_TOKEN= your_auth_token PROXY_HOST=127.0.0.1 PROXY_PORT=8888 ``` -------------------------------- ### Update Twilio Java SDK VoiceGrant Configuration Property Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md This snippet highlights the renaming of the `configurationProfileSid` property to `room` within the `com.twilio.jwt.accesstoken.VoiceGrant` class. This change affects both the getter and setter methods. ```Java // 7.x.x import com.twilio.jwt.accesstoken.VoiceGrant; VoiceGrant vg = new VoiceGrant(); vg.setConfigurationProfileSid("sid"); String sid = vg.getConfigurationProfileSid(); ``` ```Java // 8.x.x import com.twilio.jwt.accesstoken.VoiceGrant; VoiceGrant vg = new VoiceGrant(); vg.setRoom("sid"); String sid = vg.getRoom(); ``` -------------------------------- ### Call Events API: New Resource Endpoint Source: https://github.com/twilio/twilio-java/blob/main/CHANGES.md A new resource endpoint has been added to the API for retrieving call events, accessible via a GET request to `/2010-04-01/Accounts/{account_sid}/Calls/{call_sid}/Events.json`. ```APIDOC Call Events API: - Endpoint: - `GET /2010-04-01/Accounts/{account_sid}/Calls/{call_sid}/Events.json` - Purpose: - Retrieves call events for a specific call. ``` -------------------------------- ### Deleting a Twilio Resource (7.x) Source: https://github.com/twilio/twilio-java/wiki/Java-Version-7.x-Usage-Guide Explains how to remove a Twilio resource using the `Deleter` action. It demonstrates deleting a message by its SID and checking the boolean result to confirm the operation's success. ```java boolean deleted = Message.deleter(ACCOUNT_SID, MESSAGE_SID).delete(); System.out.println(deleted); // true ``` -------------------------------- ### Initialize Twilio and Create Text Content in Java Source: https://github.com/twilio/twilio-java/blob/main/examples/Content.md This Java code snippet demonstrates the complete process of initializing the Twilio Java SDK with account credentials and then creating a new `Content` object. It shows how to construct a `ContentCreateRequest` with a locale, define `TwilioText` with a body, set up `Types` to associate the text, and include custom variables. The `Content.creator().create()` method is used to persist the content. ```Java public class ContentExamples { public static void main { Twilio.init(ACCOUNT_SID, AUTH_TOKEN); createTwilioText(); } public static void createTwilioText() { Content.ContentCreateRequest createRequest = new Content.ContentCreateRequest("es", types); Content.TwilioText twilioText = new Content.TwilioText(); twilioText.setBody("text body"); Content.Types types = new Content.Types(); types.setTwilioText(twilioText); Map variables = new HashMap<>(); variables.put("var1", "val1"); createRequest.setVariables(variables); createRequest.setFriendlyName("name"); Content newContent = Content.creator(createRequest).create(); } } ``` -------------------------------- ### Applying Beta Annotation in Java Source: https://github.com/twilio/twilio-java/blob/main/README.md Demonstrates how to use the `@Beta` annotation in Java to mark classes or methods as being in beta and subject to change, indicating that their API might evolve in future releases. ```Java @Beta public class ClassName { // Class implementation } public class ClassName { @Beta public void init() { // Implementation } } ``` -------------------------------- ### Twilio Java SDK Environment Variables Source: https://github.com/twilio/twilio-java/blob/main/README.md Lists environment variables supported by the Twilio Java SDK for configuring credentials, region, and edge. Using these variables allows skipping explicit client initialization in your code. ```APIDOC Environment Variables for Twilio Java SDK: TWILIO_ACCOUNT_SID - Description: Your Twilio Account SID. TWILIO_AUTH_TOKEN - Description: Your Twilio Auth Token. TWILIO_REGION - Description: The Twilio Region to target for API requests. TWILIO_EDGE - Description: The Twilio Edge to target for API requests within a region. ``` -------------------------------- ### Twilio Java SDK JWT Access Token Grant Deprecations Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md This section documents the deprecation of specific JWT Access Token Grants. `com.twilio.jwt.accesstoken.ConversationsGrant` has been replaced by `com.twilio.jwt.accesstoken.VoiceGrant`, and `com.twilio.jwt.accesstoken.IpMessagingGrant` has been removed without a direct replacement. ```APIDOC - com.twilio.jwt.accesstoken.ConversationsGrant has been deprecated in favor of com.twilio.jwt.accesstoken.VoiceGrant - com.twilio.jwt.accesstoken.IpMessagingGrant has no replacement ``` -------------------------------- ### Twilio Serverless API Documentation Source: https://github.com/twilio/twilio-java/blob/main/CHANGES.md Notes the addition of documentation for the Twilio Serverless API. ```APIDOC Serverless API Changes: - General: - Documentation. ``` -------------------------------- ### Initialize Twilio Client with PKCV Authentication in Java Source: https://github.com/twilio/twilio-java/blob/main/README.md This Java code snippet demonstrates the initialization of a `TwilioRestClient` using Public Key Client Validation (PKCV) authentication. It involves creating a `ValidationClient` with specific account and key SIDs, along with a private key. This custom HTTP client is then passed to the `TwilioRestClient.Builder`, enabling a more secure authentication mechanism for API requests. ```java ValidationClient httpClient = new ValidationClient(ACCOUNT_SID, key.getSid(), signingKey.getSid(), pair.getPrivate()); TwilioRestClient client = new TwilioRestClient.Builder(signingKey.getSid(), signingKey.getSecret()) .accountSid(ACCOUNT_SID) .httpClient(httpClient) .build(); ``` -------------------------------- ### Build Twilio Java JAR Skipping Tests with Maven Source: https://github.com/twilio/twilio-java/blob/main/README.md Command to build a `.jar` file for the `twilio-java` library using Maven, with an option to skip tests. This is useful for quick builds or when encountering test failures during local development. ```Shell mvn package -Dmaven.test.skip=true ``` -------------------------------- ### Updating PhoneNumber Identifier Retrieval in Twilio Java SDK Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md This snippet illustrates the removal of the `getSid()` convenience method for `PhoneNumber` resources in Twilio Java SDK version 7.10.x. The recommended approach for retrieving the identifier is now `getPhoneNumber().toString()`. ```java // 7.9.x resource.getSid(); ``` ```java // 7.10.x resource.getPhoneNumber().toString(); ``` -------------------------------- ### Change Gather `input` Parameter to Enum Type in Twilio Java Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md The `input` parameter for the `Gather` TwiML resource has changed from a `String` to a `Gather.Input` enum. This provides type safety and restricts possible values to a predefined set, such as `DTMF`. ```java // 7.16.x Gather gather = new Gather.Builder() .input("dtmf") .build(); ``` ```java // 7.17.x Gather gather = new Gather.Builder() .input(Gather.Input.DTMF) .build(); ``` -------------------------------- ### Relocate Global Event Enum to Resource-Specific Enums in Twilio Java Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md The global `com.twilio.twiml.Event` enum has been removed. Event types are now nested within their respective TwiML resources, such as `Number.Event`, improving encapsulation and clarity for status callback events. ```java // 7.16.x import com.twilio.twiml.Event; Number number = new Number.Builder("number") .statusCallbackEvents(Lists.newArrayList(Event.INITIATED)) .build(); ``` ```java // 7.17.x Number number = new Number.Builder("number") .statusCallbackEvents(Lists.newArrayList(Number.Event.INITIATED)) .build(); ``` -------------------------------- ### Twilio Preview API Updates Source: https://github.com/twilio/twilio-java/blob/main/CHANGES.md Documents changes in the Twilio Preview API, specifically the migration of `web_channels` to beta under `flex-api`. ```APIDOC Twilio Preview API Updates: - Web Channels: - Moved 'web_channels' from preview to beta under 'flex-api'. (Breaking Change) ``` -------------------------------- ### Updating Pricing Number Identifier Retrieval in Twilio Java SDK Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md This snippet details the update for retrieving number identifiers from pricing resources in Twilio Java SDK. In version 7.10.x, `getSid()` was deprecated in favor of `getNumber().toString()` for `pricing/v1/voice/Number`. ```java // 7.9.x resource.getSid(); ``` ```java // 7.10.x resource.getNumber().toString(); ``` -------------------------------- ### Run Twilio Java test suite Source: https://github.com/twilio/twilio-java/blob/main/CONTRIBUTING.md This shell command executes the full test suite for the twilio-java project. It is aliased by 'make test' and ensures that all changes pass existing tests before submission. ```shell make test ``` -------------------------------- ### Make `body` Optional for Chat Message Creation in Twilio Java Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md The `body` parameter for creating Chat Messages is now optional. Message creation can be initiated without providing a body directly in the constructor, allowing for more flexible message construction workflows. ```java // 7.14.x Message.creator("IS123", "CH123", "this is the body"); ``` ```java // 7.15.x MessageCreator creator = Message.creator("IS123", "CH123"); ``` -------------------------------- ### Twilio Flex API Configuration and Resource Updates Source: https://github.com/twilio/twilio-java/blob/main/CHANGES.md Documentation for updates to the Twilio Flex API, covering new attributes for Flex Flow, changes to Flex Configuration keys, and new operations for the channels API. ```APIDOC Twilio Flex API Updates: 1. Flex Flow: - Added `JanitorEnabled` attribute to Flex Flow. FlexFlow.JanitorEnabled: Boolean 2. Flex Configuration: - Breaking Change: Changed `features_enabled` Flex Configuration key to private. - Added `features_enabled` and `serverless_service_sids` to Flex Configuration. FlexConfiguration.features_enabled: Object FlexConfiguration.serverless_service_sids: Array[String] - Added `outbound_call_flows` object to Flex Configuration. FlexConfiguration.outbound_call_flows: Object 3. Channels API: - Added read and fetch operations to channels API. GET /Channels/{ChannelSid} GET /Channels ``` -------------------------------- ### Updating Pricing Country Identifier Retrieval in Twilio Java SDK Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md This snippet shows the change in retrieving country identifiers for pricing resources in Twilio Java SDK. The `getSid()` method was replaced by `getIsoCountry()` in version 7.10.x for `pricing/v1/messaging/Country`, `pricing/v1/phonenumber/Country`, and `pricing/v1/voice/Country`. ```java // 7.9.x resource.getSid(); ``` ```java // 7.10.x resource.getIsoCountry(); ``` -------------------------------- ### Twilio Studio API Updates Source: https://github.com/twilio/twilio-java/blob/main/CHANGES.md This entry describes a documentation update for the Twilio Studio API, specifically for the Step resource. ```APIDOC Step Resource: - Added documentation for `parent_step_sid` field. ``` -------------------------------- ### Twilio SDK Updates - Version 7.15.5 Source: https://github.com/twilio/twilio-java/blob/main/CHANGES.md This version adds programmable video keys to the API and introduces `Participants` to Video. ```APIDOC Version 7.15.5: Api: - Add programmable video keys Video: - Add `Participants` ``` -------------------------------- ### Change Gather `speechTimeout` Parameter to String Type in Twilio Java Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md The `speechTimeout` parameter for the `Gather` TwiML resource has changed from `int` to `String`. This allows it to accept both integer values (as strings) and the literal string 'auto', accommodating the API's flexibility. ```java // 7.16.x Gather gather = new Gather.Builder() .speechTimeout(5) .speechTimeout("auto") .build(); ``` ```java // 7.17.x Gather gather = new Gather.Builder() .input(Gather.Input.DTMF) .speechTimeout("5") .speechTimeout("auto") .build(); ``` -------------------------------- ### Relocate Global TwiML Language Enum to Resource-Specific Enums in Twilio Java Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md The global TwiML `Language` enum has been removed. Language types are now nested within their respective TwiML resources, such as `Say.Language`, improving encapsulation and clarity for specifying language attributes. ```java // 7.16.x Say say = new Say.Builder("I <3 Twilio") .language(Language.GB) .voice(Say.Voice.MAN) .build(); ``` ```java // 7.17.x Say say = new Say.Builder("I <3 Twilio") .language(Say.Language.EN_GB) .voice(Say.Voice.MAN) .build(); ``` -------------------------------- ### Update Enqueue TwiML `queueName` to `name` parameter in Twilio Java Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md This change updates the `Enqueue` TwiML resource builder in the Twilio Java SDK, renaming the `queueName` parameter to `name` for consistency. This affects how queues are specified when building an `Enqueue` object. ```java // 7.16.x Enqueue e = new Enqueue.Builder() .queueName("queue") .build(); System.out.println(e.queueName); ``` ```java // 7.17.x Enqueue e = new Enqueue.Builder() .name("queue") .build(); System.out.println(e.name); ``` -------------------------------- ### Default Twilio Client Initialization and SMS Sending Source: https://github.com/twilio/twilio-java/blob/main/advanced-examples/custom-http-client.md This snippet demonstrates the default way to initialize the Twilio Java Helper Library and send an SMS message without any custom HTTP client configuration. It uses the `Twilio.init` method with account SID and auth token, then creates a message using the `Message.creator`. ```java Twilio.init(ACCOUNT_SID, AUTH_TOKEN); Message message = Message.creator(new PhoneNumber("+15558675310"), new PhoneNumber("+15017122661"), "Hey there!").create(); ``` -------------------------------- ### Standardize HTTP Method Type in Twilio Java TwiML Source: https://github.com/twilio/twilio-java/blob/main/UPGRADE.md This code shows the standardization of HTTP method types in Twilio Java SDK 7.17.x. The `Method` enum from `com.twilio.twiml` has been replaced by `HttpMethod` from `com.twilio.http`, aligning with the rest of the library's conventions. ```java // 7.16.x import com.twilio.twiml.Method; Conference conference = new Conference.Builder("my conference") .statusCallbackMethod(Method.GET) .build(); ``` ```java // 7.17.x import com.twilio.http.HttpMethod; Conference conference = new Conference.Builder("my conference") .statusCallbackMethod(HttpMethod.GET) .build(); ``` -------------------------------- ### Twilio Preview API and Feature Evolution Source: https://github.com/twilio/twilio-java/blob/main/CHANGES.md Updates to Twilio's preview APIs, covering changes in Authy, Understand (now Autopilot), and general preview endpoints. This includes renaming, deprecations, new resource additions, and parameter handling for challenges and factors. ```APIDOC Preview: - Authy Preview Endpoints: - Removed Authy version from 'preview' subdomain (breaking change) - Deprecated Authy endpoints from 'preview' to 'authy' subdomain - Renamed response headers for Challenge and Factors Signatures - Supported 'totp' in Authy preview endpoints - Allowed 'latest' in Authy Challenges endpoints - Add 'Form' resource given a 'form_type' - Add initial api-definitions in Services, Entities, Factors, Challenges - Understand (now Autopilot): - Renamed Understand intent to task (breaking change) - Add 'Actions' endpoints and remove 'ResponseUrl' from assistants - Add new Intent Statistics endpoint - Remove 'ttl' from Assistants ``` -------------------------------- ### Add Twilio Java Dependency with Maven Source: https://github.com/twilio/twilio-java/blob/main/README.md XML configuration for adding the `twilio-java` library as a dependency to a Maven project. This snippet specifies the group ID, artifact ID, version, and scope required for Maven to download and include the SDK. ```XML com.twilio.sdk twilio 10.X.X compile ``` -------------------------------- ### Send SMS via Proxied Twilio Client in Java Source: https://github.com/twilio/twilio-java/blob/main/advanced-examples/custom-http-client.md This Java console application demonstrates the end-to-end process of sending an SMS message using the Twilio SDK configured to operate through a proxy server. It loads necessary credentials and proxy settings from a `.env` file, initializes the Twilio SDK with the custom proxied client created by `ProxiedTwilioClientCreator`, and then proceeds to send an SMS. ```Java // Install the Java helper library from twilio.com/docs/java/install import com.twilio.Twilio; import com.twilio.http.TwilioRestClient; import com.twilio.rest.api.v2010.account.Message; import com.twilio.type.PhoneNumber; import io.github.cdimascio.dotenv.Dotenv; public class Example { public static void main(String args[]) { Dotenv dotenv = Dotenv.configure().directory(".").load(); String ACCOUNT_SID = dotenv.get("ACCOUNT_SID"); String AUTH_TOKEN = dotenv.get("AUTH_TOKEN"); String PROXY_HOST = dotenv.get("PROXY_HOST"); int PROXY_PORT = Integer.parseInt(dotenv.get("PROXY_PORT")); Twilio.init(ACCOUNT_SID, AUTH_TOKEN); ProxiedTwilioClientCreator clientCreator = new ProxiedTwilioClientCreator( ACCOUNT_SID, AUTH_TOKEN, PROXY_HOST, PROXY_PORT ); TwilioRestClient twilioRestClient = clientCreator.getClient(); Twilio.setRestClient(twilioRestClient); Message message = Message.creator( new PhoneNumber("+15558675310"), new PhoneNumber("+15017122661"), "Hey there!" ) .create(); System.out.println(message.getSid()); } } ``` -------------------------------- ### Twilio SDK Updates - Version 7.15.0 Source: https://github.com/twilio/twilio-java/blob/main/CHANGES.md This version makes members accessible through identity and channel subresources accessible by unique name in Chat. It also sets the get list 'max_page_size' to 100, adds service instance webhook retry configuration, and introduces media message capability. ```APIDOC Version 7.15.0: Chat: - Make member accessible through identity - Make channel subresources accessible by channel unique name - Set get list 'max_page_size' parameter to 100 - Add service instance webhook retry configuration - Add media message capability ``` -------------------------------- ### Create Reusable Proxied Twilio Client in Java Source: https://github.com/twilio/twilio-java/blob/main/advanced-examples/custom-http-client.md This Java class provides a reusable mechanism to construct a `TwilioRestClient` that routes its HTTP requests through a specified proxy server. It encapsulates the logic for creating and configuring a custom `HttpClient` using Apache HttpClient components, including connection pooling and proxy settings, before injecting this client into the Twilio SDK's `TwilioRestClient.Builder`. ```Java import com.twilio.http.HttpClient; import com.twilio.http.NetworkHttpClient; import com.twilio.http.TwilioRestClient; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; public class ProxiedTwilioClientCreator { private String username; private String password; private String proxyHost; private int proxyPort; private HttpClient httpClient; /** * Constructor for ProxiedTwilioClientCreator * @param username * @param password * @param proxyHost * @param proxyPort */ public ProxiedTwilioClientCreator( String username, String password, String proxyHost, int proxyPort ) { this.username = username; this.password = password; this.proxyHost = proxyHost; this.proxyPort = proxyPort; } /** * Creates a custom HttpClient based on default config as seen on: * {@link com.twilio.http.NetworkHttpClient#NetworkHttpClient() constructor} */ private void createHttpClient() { RequestConfig config = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(30500).build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setDefaultMaxPerRoute(10); connectionManager.setMaxTotal(10 * 2); HttpHost proxy = new HttpHost(proxyHost, proxyPort); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder .setConnectionManager(connectionManager) .setProxy(proxy) .setDefaultRequestConfig(config); // Inclusion of Twilio headers and build() is executed under this constructor this.httpClient = new NetworkHttpClient(clientBuilder); } /** * Get the custom client or builds a new one * @return a TwilioRestClient object */ public TwilioRestClient getClient() { if (this.httpClient == null) { this.createHttpClient(); } TwilioRestClient.Builder builder = new TwilioRestClient.Builder( username, password ); return builder.httpClient(this.httpClient).build(); } } ```