### Build Vonage Java SDK with Maven Source: https://github.com/vonage/vonage-java-sdk/blob/main/README.md Clones the Vonage Java SDK repository and builds an uberjar with all dependencies included. The resulting JAR is placed in the 'target' directory and installed in the local Maven repository. ```bash git clone git@github.com:vonage/vonage-java-sdk.git mvn install -P uberjar ``` -------------------------------- ### Make Custom GET Request with Java SDK Source: https://github.com/vonage/vonage-java-sdk/blob/main/README.md Demonstrates how to make a custom GET request to a Vonage API endpoint using the CustomClient. The response can be deserialized into a specific object or a generic Map. ```java BalanceResponse response = client.getCustomClient().get("https://rest.nexmo.com/account/get-balance"); ``` ```java Map response = client.getCustomClient().get("https://api-eu.vonage.com/v3/media?order=ascending&page_size=50"); ``` ```java String response = client.getCustomClient().get("https://example.com"); ``` -------------------------------- ### Make Custom HTTP Requests with Vonage Java SDK Source: https://context7.com/vonage/vonage-java-sdk/llms.txt This snippet demonstrates how to use the CustomClient to make various HTTP requests (GET, POST, PATCH, DELETE) to Vonage API endpoints. It shows how to handle responses as Maps or typed objects and how to send request payloads. Requires v9.1.0 or higher of the SDK. ```java import com.vonage.client.CustomClient; import java.util.Map; // Get custom client instance (available since v9.1.0) CustomClient customClient = client.getCustomClient(); // GET request returning Map try { Map balance = customClient.get("https://rest.nexmo.com/account/get-balance"); System.out.println("Balance: " + balance.get("value")); System.out.println("Auto-reload: " + balance.get("autoReload")); } catch (Exception e) { System.err.println("Request failed: " + e.getMessage()); } // POST request with Map payload Map requestBody = Map.of( "name", "Demo Application", "capabilities", Map.of( "voice", Map.of( "webhooks", Map.of( "answer_url", Map.of("address", "https://example.com/answer") ) ) ) ); Map appResponse = customClient.post( "https://api.nexmo.com/v2/applications", requestBody ); // GET request with typed response // Assuming 'Application' is a defined class // Application app = customClient.get( // "https://api.nexmo.com/v2/applications/" + appId // ); // PATCH request to update resource customClient.patch( "https://api.nexmo.com/v2/applications/" + appId, Map.of("name", "Updated Name") ); // DELETE request customClient.delete("https://api.nexmo.com/v2/applications/" + appId); ``` -------------------------------- ### Customize VonageClient Request Timeout with HttpConfig (Java) Source: https://github.com/vonage/vonage-java-sdk/blob/main/README.md Illustrates how to set a custom request timeout for the Vonage SDK using HttpConfig. The default timeout is 1 minute. This example sets the timeout to 12 seconds (12,000 milliseconds). ```java VonageClient client = VonageClient.builder() .applicationId(APPLICATION_ID) .privateKeyPath(PRIVATE_KEY_PATH) .httpConfig(HttpConfig.builder().timeoutMillis(12_000).build()) .build(); ``` -------------------------------- ### Build and Package Java SDK Release Source: https://github.com/vonage/vonage-java-sdk/wiki/Releasing-nexmo-java Executes Gradle tasks to build the project, run tests, create ZIP distribution, and generate Javadoc artifacts for release. ```bash gradle clean test gradle build gradle zip ``` -------------------------------- ### Instantiate VonageClient with Default Configuration (Java) Source: https://github.com/vonage/vonage-java-sdk/blob/main/README.md Demonstrates the default instantiation of the VonageClient using API key and secret, or private key and application ID. It's recommended to provide both for maximum compatibility. The SDK will build the client based on the provided credentials. ```java VonageClient client = VonageClient.builder() .applicationId(APPLICATION_ID) .privateKeyPath(PRIVATE_KEY_PATH) .apiKey(API_KEY) .apiSecret(API_SECRET) .build(); ``` -------------------------------- ### Configure Gradle Properties for Maven Central Release Source: https://github.com/vonage/vonage-java-sdk/wiki/Releasing-nexmo-java Sets up the gradle.properties file with necessary credentials and signing information for releasing to Maven Central. Requires GPG keys in the publishing directory. ```properties signing.keyId=67345417 signing.password=PASSWORD_GOES_HERE signing.secretKeyRingFile=./publishing/secring.gpg maven.username=USERNAME_GOES_HERE maven.password=PASSWORD_GOES_HERE ``` -------------------------------- ### Create Release Branch Using Git Source: https://github.com/vonage/vonage-java-sdk/wiki/Releasing-nexmo-java Creates a new release branch from the develop branch following semantic versioning conventions. ```bash git checkout -b x.y.z-release develop ``` -------------------------------- ### Upload Archives to Maven Central Source: https://github.com/vonage/vonage-java-sdk/wiki/Releasing-nexmo-java Publishes the built artifacts to Maven Central repository. May require manual promotion in Sonatype dashboard for non-snapshot releases. ```bash gradle uploadArchives ``` -------------------------------- ### Initialize Vonage Client in Java Source: https://context7.com/vonage/vonage-java-sdk/llms.txt Initializes the Vonage client with various authentication methods and configurations. Supports API key, JWT, and custom HTTP settings for different API compatibility needs. ```java import com.vonage.client.VonageClient; import java.nio.file.Paths; // Initialize with both API key and JWT authentication for maximum API compatibility VonageClient client = VonageClient.builder() .apiKey("your_api_key") .apiSecret("your_api_secret") .applicationId("your_application_id") .privateKeyPath("path/to/private.key") .build(); // Alternative: Initialize with just API key for SMS and Number Insight APIs VonageClient simpleClient = VonageClient.builder() .apiKey("your_api_key") .apiSecret("your_api_secret") .build(); // With custom HTTP configuration (timeout, proxy, base URI) HttpConfig httpConfig = HttpConfig.builder() .timeoutMillis(30000) .apiBaseUri("https://api.nexmo.com") .build(); VonageClient customClient = VonageClient.builder() .apiKey("your_api_key") .apiSecret("your_api_secret") .httpConfig(httpConfig) .build(); ``` -------------------------------- ### Application Management: Create, List, Update, Delete (Java) Source: https://context7.com/vonage/vonage-java-sdk/llms.txt Provides Java code for managing Vonage applications, including creation with specified capabilities (Voice, Messages), listing existing applications, updating application details, and deleting applications. This functionality relies on the Vonage client and `ApplicationClient`. It takes application configuration objects as input and returns application details or lists of applications. ```java import com.vonage.client.application.ApplicationClient; import com.vonage.client.application.Application; import com.vonage.client.application.capabilities.*; import java.util.UUID; // Get Application client instance ApplicationClient appClient = client.getApplicationClient(); // Create application with Voice and Messages capabilities Application newApp = Application.builder() .name("My Communication App") .voice(Voice.builder() .addWebhook(Webhook.Type.ANSWER, "https://example.com/webhooks/answer") .addWebhook(Webhook.Type.EVENT, "https://example.com/webhooks/events") .build()) .messages(Messages.builder() .addWebhook(Webhook.Type.INBOUND, "https://example.com/webhooks/inbound") .addWebhook(Webhook.Type.STATUS, "https://example.com/webhooks/status") .build()) .build(); try { Application createdApp = appClient.createApplication(newApp); UUID applicationId = createdApp.getId(); System.out.println("Application created: " + applicationId); System.out.println("Name: " + createdApp.getName()); System.out.println("Private key: " + createdApp.getPrivateKey()); // List all applications List apps = appClient.listApplications().getApplications(); for (Application app : apps) { System.out.println(app.getId() + ": " + app.getName()); } // Get application details Application retrievedApp = appClient.getApplication(applicationId.toString()); // Update application Application updatedApp = Application.builder(retrievedApp) .name("My Updated App") .build(); appClient.updateApplication(updatedApp); // Delete application appClient.deleteApplication(applicationId.toString()); } catch (Exception e) { System.err.println("Application operation failed: " + e.getMessage()); } ``` -------------------------------- ### Configure Proxy for VonageClient with HttpConfig (Java) Source: https://github.com/vonage/vonage-java-sdk/blob/main/README.md Demonstrates how to configure a proxy server for requests made by the Vonage SDK using the `proxy` method on HttpConfig.Builder. This allows requests to be routed through a specified proxy server. ```java VonageClient client = VonageClient.builder() .applicationId(APPLICATION_ID) .privateKeyPath(PRIVATE_KEY_PATH) .httpConfig(HttpConfig.builder().proxy("https://myserver.example.com").build()) .build(); ``` -------------------------------- ### Make Outbound Calls with Vonage Java SDK Source: https://context7.com/vonage/vonage-java-sdk/llms.txt Demonstrates creating and managing outbound voice calls using the Vonage Java SDK, supporting inline NCCO for call actions or webhook-based configurations. Requires a VoiceClient instance and phone endpoints; handles call creation, details retrieval, DTMF sending, and call modifications like earmuffing. Limitations include dependency on Vonage credentials and network connectivity; exceptions are caught for error handling. ```java import com.vonage.client.voice.VoiceClient; import com.vonage.client.voice.Call; import com.vonage.client.voice.CallEvent; import com.vonage.client.voice.CallInfo; import com.vonage.client.voice.PhoneEndpoint; import com.vonage.client.voice.ncco.*; // Get Voice client instance VoiceClient voiceClient = client.getVoiceClient(); // Method 1: Make a call with NCCO actions (inline) Collection ncco = Arrays.asList( TalkAction.builder("Hello, this is a call from Vonage") .language(TextToSpeechLanguage.ENGLISH_UNITED_STATES) .build() ); Call outboundCall = Call.builder() .to(new PhoneEndpoint("447700900000")) .from(new PhoneEndpoint("447700900001")) .ncco(ncco) .build(); try { CallEvent event = voiceClient.createCall(outboundCall); String callUuid = event.getUuid(); System.out.println("Call created with UUID: " + callUuid); System.out.println("Call status: " + event.getStatus()); System.out.println("Call direction: " + event.getDirection()); // Get call details CallInfo callInfo = voiceClient.getCallDetails(callUuid); System.out.println("Call duration: " + callInfo.getDuration()); System.out.println("Call price: " + callInfo.getPrice()); // Send DTMF tones during call voiceClient.sendDtmf(callUuid, "1234"); // Modify call - earmuff (prevent hearing audio) voiceClient.earmuffCall(callUuid); // Modify call - unearmuff (allow hearing audio again) voiceClient.unearmuffCall(callUuid); } catch (Exception e) { System.err.println("Call failed: " + e.getMessage()); } // Method 2: Make a call with answer URL (webhook) Call webhookCall = Call.builder() .to(new PhoneEndpoint("447700900000")) .from(new PhoneEndpoint("447700900001")) .answerUrl("https://example.com/webhooks/answer") .eventUrl("https://example.com/webhooks/events") .build(); CallEvent webhookEvent = voiceClient.createCall(webhookCall); ``` -------------------------------- ### Search, Buy, and Configure Vonage Virtual Numbers (Java) Source: https://context7.com/vonage/vonage-java-sdk/llms.txt This Java code showcases the Vonage Java SDK's capabilities for number management. It includes functions to list owned virtual numbers, search for available numbers based on country, type, features, and patterns, purchase a number, and configure it with voice and SMS callbacks. It utilizes the NumbersClient and requires an initialized Vonage client. The output displays owned numbers, available numbers with cost, and confirmation of number configuration. ```java import com.vonage.client.numbers.NumbersClient; import com.vonage.client.numbers.OwnedNumber; import com.vonage.client.numbers.SearchNumbersResponse; import com.vonage.client.numbers.SearchNumbersFilter; import com.vonage.client.numbers.AvailableNumber; import com.vonage.client.numbers.UpdateNumberRequest; import com.vonage.client.numbers.Type; import com.vonage.client.numbers.Feature; import com.vonage.client.numbers.CallbackType; import com.vonage.client.numbers.MoSmppSysType; import java.util.List; // Assume 'client' is an initialized Vonage client instance // VonageClient client = new VonageClient.Builder().apiKey("YOUR_API_KEY").apiSecret("YOUR_API_SECRET").build(); // Get Numbers client instance NumbersClient numbersClient = client.getNumbersClient(); // List owned numbers try { List ownedNumbers = numbersClient.listNumbers(); for (OwnedNumber number : ownedNumbers) { System.out.println("Number: " + number.getMsisdn()); System.out.println("Country: " + number.getCountry()); System.out.println("Type: " + number.getType()); System.out.println("Features: " + number.getFeatures()); } } catch (Exception e) { System.err.println("Failed to list numbers: " + e.getMessage()); } // Search for available numbers SearchNumbersFilter filter = SearchNumbersFilter.builder() .country("GB") .type(Type.MOBILE) .features(Feature.SMS, Feature.VOICE) .pattern("447700*") .build(); SearchNumbersResponse searchResponse = numbersClient.searchNumbers(filter); List availableNumbers = searchResponse.getNumbers(); for (AvailableNumber number : availableNumbers) { System.out.println("Available: " + number.getMsisdn()); System.out.println("Cost: " + number.getCost()); System.out.println("Type: " + number.getType()); } // Buy a number if (!availableNumbers.isEmpty()) { String numberToBuy = availableNumbers.get(0).getMsisdn(); numbersClient.buyNumber(numberToBuy, "GB"); System.out.println("Purchased number: " + numberToBuy); } // Configure number with webhooks UpdateNumberRequest updateRequest = UpdateNumberRequest.builder("447700900000", "GB") .voiceCallbackType(CallbackType.APP) .voiceCallbackValue("your-application-id") // Replace with your application ID .moSmppSysType(MoSmppSysType.INBOUND) .voiceStatusCallback("https://example.com/webhooks/voice-status") .build(); numbersClient.updateNumber(updateRequest); System.out.println("Number configured successfully"); ``` -------------------------------- ### Tag Release Version in Git Source: https://github.com/vonage/vonage-java-sdk/wiki/Releasing-nexmo-java Tags the current commit with the release version and pushes tags to remote repository. Forces tag update if needed. ```bash git tag -f vx.y.z git push --tags ``` -------------------------------- ### Merge Release Branch to Master Source: https://github.com/vonage/vonage-java-sdk/wiki/Releasing-nexmo-java Merges the release branch into master using no-fast-forward strategy and pushes changes to remote repository. ```bash git checkout master git merge --no-ff x.y.z-release git push ``` -------------------------------- ### Gradle Dependency for Vonage Java SDK Source: https://github.com/vonage/vonage-java-sdk/blob/main/README.md This snippet shows how to add the Vonage Server SDK as a dependency in a Gradle project. It requires Java 8 or higher and should be placed in the build.gradle or build.gradle.kts file. ```groovy dependencies { implementation("com.vonage:server-sdk:9.4.2") } ``` -------------------------------- ### Manage Vonage Account Balance, Settings, and API Secrets (Java) Source: https://context7.com/vonage/vonage-java-sdk/llms.txt This Java code snippet demonstrates how to use the Vonage Java SDK to retrieve account balance information, update account settings like SMS and delivery receipt URLs, and list API secrets associated with an account. It requires the Vonage Java SDK and an initialized Vonage client. The output includes account balance details, auto-reload status, and updated settings parameters. It also lists secret IDs and creation timestamps. ```java import com.vonage.client.account.AccountClient; import com.vonage.client.account.BalanceResponse; import com.vonage.client.account.SettingsResponse; import com.vonage.client.account.SettingsRequest; import com.vonage.client.account.SecretInfo; import java.util.List; // Assume 'client' is an initialized Vonage client instance // VonageClient client = new VonageClient.Builder().apiKey("YOUR_API_KEY").apiSecret("YOUR_API_SECRET").build(); // Get Account client instance AccountClient accountClient = client.getAccountClient(); // Get account balance try { BalanceResponse balance = accountClient.getBalance(); System.out.println("Account balance: " + balance.getValue() + " " + balance.getCurrency()); System.out.println("Auto-reload enabled: " + balance.getAutoReload()); } catch (Exception e) { System.err.println("Failed to get balance: " + e.getMessage()); } // Update account settings SettingsRequest settingsRequest = SettingsRequest.builder() .incomingSmsUrl("https://example.com/webhooks/inbound-sms") .deliveryReceiptUrl("https://example.com/webhooks/delivery-receipt") .build(); try { SettingsResponse settingsResponse = accountClient.updateSettings(settingsRequest); System.out.println("Max outbound requests/sec: " + settingsResponse.getMaxOutboundRequest()); System.out.println("Max inbound messages/sec: " + settingsResponse.getMaxInboundMessage()); System.out.println("Max calls/sec: " + settingsResponse.getMaxCalls()); } catch (Exception e) { System.err.println("Failed to update settings: " + e.getMessage()); } // List API secrets String apiKey = "your_api_key"; // Replace with your actual API key if different from default List secrets = accountClient.listSecrets(apiKey).getSecrets(); for (SecretInfo secret : secrets) { System.out.println("Secret ID: " + secret.getId()); System.out.println("Created at: " + secret.getCreatedAt()); } ``` -------------------------------- ### Maven Dependency for Vonage Java SDK Source: https://github.com/vonage/vonage-java-sdk/blob/main/README.md This snippet demonstrates how to include the Vonage Server SDK in a Maven project. Add this to the section of your pom.xml file. Requires Java 8+. ```xml com.vonage server-sdk 9.4.2 ``` -------------------------------- ### Custom POST Request with Java SDK Source: https://github.com/vonage/vonage-java-sdk/blob/main/README.md Illustrates making custom POST requests using the CustomClient, showing flexibility in handling request and response bodies. Supports Map-based or Jsonable object requests and responses. ```java Map response = client.getCustomClient().post( "https://api.nexmo.com/v2/applications", Map.of("name", "Demo Application") ); ``` ```java Application response = client.getCustomClient().post( "https://api.nexmo.com/v2/applications", Map.of("name", "Demo Application") ); ``` ```java Map response = client.getCustomClient().post( "https://api.nexmo.com/v2/applications", Application.builder().name("Demo Application").build() ); ``` ```java Application response = client.getCustomClient().post( "https://api.nexmo.com/v2/applications", Application.builder().name("Demo Application").build() ); ``` -------------------------------- ### Verify API v2 - User Verification (Java) Source: https://context7.com/vonage/vonage-java-sdk/llms.txt This snippet demonstrates how to verify users using the Vonage Verify API v2. It covers initiating verification with SMS, WhatsApp, Voice, and Email workflows, as well as checking the verification code entered by the user. It uses the Vonage Java SDK and handles potential exceptions during verification. ```Java import com.vonage.client.verify2.Verify2Client; import com.vonage.client.verify2.VerificationRequest; import com.vonage.client.verify2.VerificationResponse; import com.vonage.client.verify2.VerifyCodeResponse; import com.vonage.client.verify2.SmsWorkflow; import com.vonage.client.verify2.VoiceWorkflow; import com.vonage.client.verify2.WhatsappWorkflow; import com.vonage.client.verify2.EmailWorkflow; import java.util.UUID; // Get Verify2 client instance Verify2Client verify2Client = client.getVerify2Client(); // Start verification with SMS workflow VerificationRequest request = VerificationRequest.builder() .brand("MyCompany") .addWorkflow(new SmsWorkflow("447700900000")) .codeLength(6) .build(); try { VerificationResponse verifyResponse = verify2Client.sendVerification(request); UUID requestId = verifyResponse.getRequestId(); System.out.println("Verification request ID: " + requestId); System.out.println("Check URL: " + verifyResponse.getCheckUrl()); // Check the code provided by user String userCode = "123456"; // Code entered by user VerifyCodeResponse checkResponse = verify2Client.checkVerificationCode(requestId, userCode); System.out.println("Verification status: " + checkResponse.getStatus()); if (checkResponse.getStatus() == VerificationStatus.COMPLETED) { System.out.println("User verified successfully!"); } } catch (VerifyResponseException e) { System.err.println("Verification failed: " + e.getMessage()); } // Multi-channel verification with fallback (WhatsApp, then Voice) VerificationRequest multiChannel = VerificationRequest.builder() .brand("MyCompany") .addWorkflow(new WhatsappWorkflow("447700900000")) .addWorkflow(new VoiceWorkflow("447700900000")) .channelTimeout(180) // Wait 3 minutes before trying next workflow .codeLength(4) .build(); VerificationResponse multiResponse = verify2Client.sendVerification(multiChannel); // Email verification VerificationRequest emailRequest = VerificationRequest.builder() .brand("MyCompany") .addWorkflow(EmailWorkflow.builder("user@example.com") .from("noreply@mycompany.com") .build()) .build(); VerificationResponse emailResponse = verify2Client.sendVerification(emailRequest); ``` -------------------------------- ### Configure Java SDK Logging Source: https://github.com/vonage/vonage-java-sdk/blob/main/README.md Configure logging levels for the Vonage Java SDK using Java's built-in logging library. This allows you to log requests and responses at a detailed level. Requires importing java.util.logging.* classes. Outputs detailed logs when level is set to FINE. ```java LogManager.getLogManager().getLogger("com.vonage.client.AbstractMethod").setLevel(Level.FINE); ``` ```java LogManager.getLogManager().getLogger("").setLevel(Level.FINE); ``` -------------------------------- ### Messages API - Multi-Channel Messaging (Java) Source: https://context7.com/vonage/vonage-java-sdk/llms.txt This snippet showcases sending messages using the Vonage Messages API, supporting SMS, WhatsApp, Viber, and Facebook Messenger. It demonstrates sending simple text messages, WhatsApp templates, and WhatsApp images, while handling potential errors during message sending. ```Java import com.vonage.client.messages.MessagesClient; import com.vonage.client.messages.MessageResponse; import com.vonage.client.messages.sms.SmsTextRequest; import com.vonage.client.messages.whatsapp.*; import com.vonage.client.messages.viber.ViberTextRequest; import com.vonage.client.messages.messenger.MessengerTextRequest; import java.util.UUID; // Get Messages client instance MessagesClient messagesClient = client.getMessagesClient(); // Send SMS via Messages API SmsTextRequest smsRequest = SmsTextRequest.builder() .from("VonageAPIs") .to("447700900000") .text("Hello via Messages API!") .build(); try { MessageResponse smsResponse = messagesClient.sendMessage(smsRequest); UUID messageUuid = smsResponse.getMessageUuid(); System.out.println("Message sent with UUID: " + messageUuid); } catch (MessageResponseException e) { System.err.println("Failed to send: " + e.getMessage()); } // Send WhatsApp text message WhatsappTextRequest whatsappText = WhatsappTextRequest.builder() .from("447700900001") .to("447700900000") .text("Hello from WhatsApp!") .build(); MessageResponse whatsappResponse = messagesClient.sendMessage(whatsappText); // Send WhatsApp template message WhatsappTemplateRequest templateRequest = WhatsappTemplateRequest.builder() .from("447700900001") .to("447700900000") .template(Template.builder() .name("welcome_message") .parameters("John", "Doe") .build()) .build(); MessageResponse templateResponse = messagesClient.sendMessage(templateRequest); // Send WhatsApp image WhatsappImageRequest imageRequest = WhatsappImageRequest.builder() .from("447700900001") .to("447700900000") .url("https://example.com/image.jpg") .caption("Check out this image!") .build(); MessageResponse imageResponse = messagesClient.sendMessage(imageRequest); // Send Viber message ViberTextRequest viberRequest = ViberTextRequest.builder() .from("VonageAPIs") .to("447700900000") .text("Hello from Viber!") .build(); MessageResponse viberResponse = messagesClient.sendMessage(viberRequest); ``` -------------------------------- ### POST /verify2 - User Verification Source: https://context7.com/vonage/vonage-java-sdk/llms.txt This endpoint allows sending verification codes via multiple channels including SMS, voice, email, WhatsApp, or silent authentication. It supports multi-channel verification with fallback options. ```APIDOC ## POST /verify2 ### Description Send verification codes via SMS, voice, email, WhatsApp, or silent authentication. Supports multi-channel verification with fallback options. ### Method POST ### Endpoint /verify2 ### Parameters #### Request Body - **brand** (string) - Required - The brand name for the verification. - **workflows** (array) - Required - List of workflows for verification (SMS, Voice, WhatsApp, Email). - **codeLength** (integer) - Optional - Length of the verification code (default: 4). - **channelTimeout** (integer) - Optional - Timeout before trying next workflow in seconds. ### Request Example ```json { "brand": "MyCompany", "workflows": [ { "channel": "sms", "to": "447700900000" } ], "codeLength": 6 } ``` ### Response #### Success Response (200) - **requestId** (UUID) - Unique identifier for the verification request. - **checkUrl** (string) - URL to check the verification status. #### Response Example ```json { "requestId": "123e4567-e89b-12d3-a456-426614174000", "checkUrl": "https://api.vonage.com/verify2/check/123e4567-e89b-12d3-a456-426614174000" } ``` ``` -------------------------------- ### Handle API Errors with Vonage Java SDK Source: https://context7.com/vonage/vonage-java-sdk/llms.txt This snippet illustrates how to catch and handle various Vonage SDK exceptions for different APIs like SMS, Voice, Verify, and Messages. It shows how to access specific error details such as status codes and messages for effective error management. ```java import com.vonage.client.VonageClientException; import com.vonage.client.VonageResponseParseException; import com.vonage.client.voice.VoiceResponseException; import com.vonage.client.verify2.VerifyResponseException; import com.vonage.client.messages.MessageResponseException; // Import necessary classes for SMS, Voice, Verify, Messages APIs // import com.vonage.client.sms.SmsSubmissionResponse; // import com.vonage.client.sms.SmsSubmissionResponseMessage; // import com.vonage.client.sms.MessageStatus; // import com.vonage.client.voice.CallEvent; // import com.vonage.client.verify2.VerificationResponse; // import com.vonage.client.messages.MessageResponse; // SMS error handling try { // SmsSubmissionResponse response = smsClient.submitMessage(message); // for (SmsSubmissionResponseMessage msg : response.getMessages()) { // if (msg.getStatus() != MessageStatus.OK) { // System.err.println("Status: " + msg.getStatus()); // System.err.println("Error: " + msg.getErrorText()); // } // } } catch (VonageClientException e) { System.err.println("API error: " + e.getMessage()); } catch (VonageResponseParseException e) { System.err.println("Parse error: " + e.getMessage()); } // Voice API error handling try { // CallEvent event = voiceClient.createCall(call); } catch (VoiceResponseException e) { System.err.println("Voice error: " + e.getMessage()); System.err.println("HTTP status: " + e.getStatusCode()); } // Verify API error handling with specific status codes try { // VerificationResponse response = verify2Client.sendVerification(request); } catch (VerifyResponseException e) { int statusCode = e.getStatusCode(); switch (statusCode) { case 409: System.err.println("Concurrent verification in progress"); break; case 422: System.err.println("Invalid parameters: " + e.getMessage()); break; case 429: System.err.println("Rate limit exceeded"); break; default: System.err.println("Error: " + e.getMessage()); } } // Messages API error handling try { // MessageResponse response = messagesClient.sendMessage(messageRequest); } catch (MessageResponseException e) { System.err.println("Message failed: " + e.getMessage()); System.err.println("Status code: " + e.getStatusCode()); } ``` -------------------------------- ### Number Insight API: Basic, Standard, and Advanced Insight (Java) Source: https://context7.com/vonage/vonage-java-sdk/llms.txt Demonstrates how to use the Vonage Java SDK to perform basic, standard, and advanced number insights. This includes validating number details, retrieving carrier information, and checking reachability and roaming status. It requires the Vonage client and SDK. The input is a phone number string, and the output is a response object containing detailed insight information. ```java import com.vonage.client.insight.InsightClient; import com.vonage.client.insight.BasicInsightResponse; import com.vonage.client.insight.StandardInsightResponse; import com.vonage.client.insight.AdvancedInsightResponse; // Get Insight client instance InsightClient insightClient = client.getInsightClient(); // Basic Insight - Free, synchronous number validation try { BasicInsightResponse basicResponse = insightClient.getBasicNumberInsight("447700900000"); System.out.println("Status: " + basicResponse.getStatus()); System.out.println("International format: " + basicResponse.getInternationalFormatNumber()); System.out.println("National format: " + basicResponse.getNationalFormatNumber()); System.out.println("Country: " + basicResponse.getCountryName()); System.out.println("Country code: " + basicResponse.getCountryCode()); } catch (Exception e) { System.err.println("Insight failed: " + e.getMessage()); } // Standard Insight - Includes carrier and number type StandardInsightResponse standardResponse = insightClient.getStandardNumberInsight("447700900000"); System.out.println("Current carrier: " + standardResponse.getCurrentCarrier().getName()); System.out.println("Original carrier: " + standardResponse.getOriginalCarrier().getName()); System.out.println("Number type: " + standardResponse.getNumberType()); System.out.println("Ported: " + standardResponse.getPorted()); // Advanced Insight - Real-time number reachability AdvancedInsightResponse advancedResponse = insightClient.getAdvancedNumberInsight("447700900000"); System.out.println("Reachable: " + advancedResponse.getReachable()); System.out.println("Roaming status: " + advancedResponse.getRoaming().getStatus()); System.out.println("Roaming country: " + advancedResponse.getRoaming().getRoamingCountryCode()); System.out.println("Valid number: " + advancedResponse.getValidNumber()); System.out.println("IP address: " + advancedResponse.getIpAddress()); ``` -------------------------------- ### Stream Audio and TTS with Vonage Java SDK Source: https://context7.com/vonage/vonage-java-sdk/llms.txt Shows how to stream audio files or play text-to-speech during active voice calls using the Vonage Java SDK. Requires an active call UUID and payloads for streaming or talking; supports looping, volume levels, and stopping streams. Outputs responses indicating success or failure; limited to active calls and requires valid audio URLs for streaming. ```java import com.vonage.client.voice.StreamPayload; import com.vonage.client.voice.StreamResponse; import com.vonage.client.voice.TalkPayload; import com.vonage.client.voice.TalkResponse; // Stream audio file to active call String callUuid = "63f61863-4a51-4f6b-86e1-46edebcf9356"; StreamPayload streamPayload = StreamPayload.builder(callUuid) .addStreamUrl("https://example.com/audio/hold-music.mp3") .loop(3) // Play 3 times .level(0.5) // Volume level 0.0 to 1.0 .build(); try { StreamResponse streamResponse = voiceClient.startStream(streamPayload); System.out.println("Stream started: " + streamResponse.getMessage()); // Stop the stream StreamResponse stopResponse = voiceClient.stopStream(callUuid); System.out.println("Stream stopped: " + stopResponse.getMessage()); } catch (Exception e) { System.err.println("Stream failed: " + e.getMessage()); } // Play text-to-speech to active call TalkPayload talkPayload = TalkPayload.builder("Please hold while we connect you") .uuid(callUuid) .language(TextToSpeechLanguage.ENGLISH_UNITED_STATES) .style(1) // Voice style .loop(2) .level(0.8) .build(); try { TalkResponse talkResponse = voiceClient.startTalk(talkPayload); System.out.println("TTS started: " + talkResponse.getMessage()); // Stop text-to-speech TalkResponse stopTalk = voiceClient.stopTalk(callUuid); } catch (Exception e) { System.err.println("TTS failed: " + e.getMessage()); } ``` -------------------------------- ### POST /messages - Multi-Channel Messaging Source: https://context7.com/vonage/vonage-java-sdk/llms.txt This endpoint allows sending messages via multiple channels including SMS, MMS, WhatsApp, Viber, and Facebook Messenger. It supports text, template, and media messages. ```APIDOC ## POST /messages ### Description Send messages via multiple channels including SMS, MMS, WhatsApp, Viber, and Facebook Messenger. Supports text, template, and media messages. ### Method POST ### Endpoint /messages ### Parameters #### Request Body - **from** (string) - Required - The sender's phone number or identifier. - **to** (string) - Required - The recipient's phone number. - **text** (string) - Optional - The text content of the message (for text messages). - **url** (string) - Optional - The URL of the media (for media messages). - **caption** (string) - Optional - The caption for the media (for media messages). - **template** (object) - Optional - The template object for template messages. ### Request Example ```json { "from": "VonageAPIs", "to": "447700900000", "text": "Hello via Messages API!" } ``` ### Response #### Success Response (200) - **messageUuid** (UUID) - Unique identifier for the sent message. #### Response Example ```json { "messageUuid": "123e4567-e89b-12d3-a456-426614174000" } ``` ``` -------------------------------- ### Send SMS Messages with Vonage Java SDK Source: https://context7.com/vonage/vonage-java-sdk/llms.txt Demonstrates sending SMS messages using the Vonage Java SDK, including basic text messages and Unicode messages for non-Latin characters. Handles response parsing and error checking. ```java import com.vonage.client.sms.SmsClient; import com.vonage.client.sms.messages.TextMessage; import com.vonage.client.sms.SmsSubmissionResponse; import com.vonage.client.sms.SmsSubmissionResponseMessage; // Get SMS client instance SmsClient smsClient = client.getSmsClient(); // Send a basic text message TextMessage message = new TextMessage( "VonageAPIs", // From (sender ID or phone number) "447700900000", // To (recipient phone number) "Hello from Vonage SDK!" // Message text ); try { SmsSubmissionResponse response = smsClient.submitMessage(message); // Check each message part (long messages are split automatically) for (SmsSubmissionResponseMessage msg : response.getMessages()) { System.out.println("Message ID: " + msg.getId()); System.out.println("Status: " + msg.getStatus()); System.out.println("Remaining balance: " + msg.getRemainingBalance()); System.out.println("Message price: " + msg.getMessagePrice()); if (msg.getStatus() != com.vonage.client.sms.MessageStatus.OK) { System.err.println("Message failed: " + msg.getErrorText()); } } } catch (Exception e) { System.err.println("Failed to send SMS: " + e.getMessage()); } // Send Unicode message (for non-Latin characters) TextMessage unicodeMessage = new TextMessage( "447700900001", "447700900000", "你好,世界!", true // Enable Unicode ); SmsSubmissionResponse unicodeResponse = smsClient.submitMessage(unicodeMessage); ``` -------------------------------- ### Add Custom Request Headers to VonageClient with HttpConfig (Java) Source: https://github.com/vonage/vonage-java-sdk/blob/main/README.md Explains how to add custom request headers to all requests made by the Vonage SDK using HttpConfig. The `addRequestHeader` method allows specifying both the header name and its value. ```java VonageClient client = VonageClient.builder() .applicationId(APPLICATION_ID) .privateKeyPath(PRIVATE_KEY_PATH) .httpConfig(HttpConfig.builder() .addRequestHeader("X-My-Header", "MyValue") .addRequestHeader("Correlation-Id", "123-456-789") .build() ) .build(); ``` -------------------------------- ### Customize VonageClient Base URIs with HttpConfig (Java) Source: https://github.com/vonage/vonage-java-sdk/blob/main/README.md Shows how to customize the base URIs for Vonage API endpoints using HttpConfig. The HttpConfig.Builder allows setting specific URIs for API, REST, EU API, and Video API. If a property is not specified, the default value is used. A single baseUri can also be set. ```java HttpConfig httpConfig = HttpConfig.builder() .apiBaseUri("https://api.example.com") .restBaseUri("https://rest.example.com") .apiEuBaseUri("https://api-eu.example.com") .videoBaseUri("https://video.example.com") .build(); VonageClient client = VonageClient.builder() .apiKey(API_KEY).apiSecret(API_SECRET) .httpConfig(httpConfig) .build(); ``` ```java HttpConfig httpConfig = HttpConfig.builder().baseUri("http://example.com").build(); VonageClient client = VonageClient.builder() .apiKey(API_KEY).apiSecret(API_SECRET) .httpConfig(httpConfig) .build(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.