diff --git a/.github/workflows/samples-compilation.yaml b/.github/workflows/samples-compilation.yaml index f279134a8..3d5c2c25e 100644 --- a/.github/workflows/samples-compilation.yaml +++ b/.github/workflows/samples-compilation.yaml @@ -1,4 +1,4 @@ -name: Snippets Compilation +name: Examples Compilation on: [push] diff --git a/examples/client/README.md b/examples/client/README.md new file mode 100644 index 000000000..f462895e5 --- /dev/null +++ b/examples/client/README.md @@ -0,0 +1,37 @@ +# Client application template based onto Sinch Java SDK + +This directory contains a client application based onto [Sinch SDK java](https://github.com/sinch/sinch-sdk-java) + +# Prerequisites + +- JDK 8 or later (Sinch SDK Java is requiring java 8 only but client application can use latest available version) +- [Maven](https://maven.apache.org/) +- [Sinch account](https://dashboard.sinch.com) + +## Configuration + +Edit [config.properties](src/main/resources/config.properties) file to set credentials to be used to configure the SinchClient. + +- To use Numbers or SMS, you need to fill the following settings with your Sinch account information: + - `SINCH_PROJECT_ID`=Your Sinch Project ID + - `SINCH_KEY_ID`=Your Sinch Key ID + - `SINCH_KEY_SECRET`=Your Sinch Key Secret +- To use [Verification](https://developers.sinch.com/docs/verification) or [Voice](https://developers.sinch.com/docs/voice) you will need application credentials and fill [config.properties](src/main/resources/config.properties) dedicated section. +- To use [SMS](https://developers.sinch.com/docs/sms) for regions other than US/EU, you will need service plan ID credentials and fill [config.properties](src/main/resources/config.properties) dedicated section. + + +## Usage + +1. Edit configuration file +See above for Configuration paragraph + +2. Application generation + + Application generation command: + ```sh + mvn package + ``` +3. Execute application + ```sh + java -jar target/sinch-java-sdk-client-application-1.0-SNAPSHOT-jar-with-dependencies.jar + ``` diff --git a/examples/client/pom.xml b/examples/client/pom.xml new file mode 100644 index 000000000..8ef76f558 --- /dev/null +++ b/examples/client/pom.xml @@ -0,0 +1,94 @@ + + + 4.0.0 + + my.company.com + sinch-java-sdk-client-application + 1.0-SNAPSHOT + jar + Sinch Java SDK Client Application + + + + use-version + + ${env.SDK_VERSION} + + + + + + [2.0.0,) + 8 + 8 + 3.13.0 + UTF-8 + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.6.0 + + + add-sources + generate-sources + + add-source + + + + src/main/java + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + Application + + + + + jar-with-dependencies + + + + + package + + single + + + + + + + + + + + com.sinch.sdk + sinch-sdk-java + ${sinch.sdk.java.version} + + + + org.slf4j + slf4j-jdk14 + 2.0.9 + + + + + diff --git a/examples/client/src/main/java/Application.java b/examples/client/src/main/java/Application.java new file mode 100644 index 000000000..87df54c03 --- /dev/null +++ b/examples/client/src/main/java/Application.java @@ -0,0 +1,82 @@ +import com.sinch.sdk.SinchClient; +import conversation.ConversationQuickStart; +import java.io.IOException; +import java.io.InputStream; +import java.util.logging.LogManager; +import java.util.logging.Logger; +import numbers.NumbersQuickStart; +import sms.SmsQuickStart; +import verification.VerificationQuickStart; +import voice.VoiceQuickStart; + +public abstract class Application { + + private static final String LOGGING_PROPERTIES_FILE = "logging.properties"; + private static final Logger LOGGER = initializeLogger(); + + public static void main(String[] args) { + try { + + SinchClient client = SinchClientHelper.initSinchClient(); + LOGGER.info("Application initiated. SinchClient ready."); + + // Conversation service dedicated business logic processing + // (see https://developers.sinch.com/docs/conversation) + // comment if unused + if (client.getConfiguration().getUnifiedCredentials().isPresent()) { + ConversationQuickStart conversation = + new ConversationQuickStart(client.conversation().v1()); + } + + // Numbers service dedicated business logic processing + // (see https://developers.sinch.com/categories/numbersandconnectivity) + // comment if unused + if (client.getConfiguration().getUnifiedCredentials().isPresent()) { + NumbersQuickStart numbers = new NumbersQuickStart(client.numbers().v1()); + } + + // SMS service dedicated business logic processing + // (see https://developers.sinch.com/docs/sms) + // comment if unused + if (client.getConfiguration().getSmsServicePlanCredentials().isPresent() + || client.getConfiguration().getUnifiedCredentials().isPresent()) { + SmsQuickStart sms = new SmsQuickStart(client.sms().v1()); + } + + // Verification service dedicated business logic processing + // (see https://developers.sinch.com/docs/verification) + // comment if unused + if (client.getConfiguration().getApplicationCredentials().isPresent()) { + VerificationQuickStart verification = + new VerificationQuickStart(client.verification().v1()); + } + + // Voice service dedicated business logic processing + // (see https://developers.sinch.com/docs/voice) + // comment if unused + if (client.getConfiguration().getApplicationCredentials().isPresent()) { + VoiceQuickStart voice = new VoiceQuickStart(client.voice().v1()); + } + + } catch (Exception e) { + LOGGER.severe(String.format("Application failure: %s", e.getMessage())); + } + } + + static Logger initializeLogger() { + try (InputStream logConfigInputStream = + Application.class.getClassLoader().getResourceAsStream(LOGGING_PROPERTIES_FILE)) { + + if (logConfigInputStream != null) { + LogManager.getLogManager().readConfiguration(logConfigInputStream); + } else { + throw new RuntimeException( + String.format("The file '%s' couldn't be loaded.", LOGGING_PROPERTIES_FILE)); + } + + } catch (IOException e) { + throw new RuntimeException(e.getMessage()); + } + return Logger.getLogger(Application.class.getName()); + } +} diff --git a/examples/client/src/main/java/SinchClientHelper.java b/examples/client/src/main/java/SinchClientHelper.java new file mode 100644 index 000000000..9e1b6a888 --- /dev/null +++ b/examples/client/src/main/java/SinchClientHelper.java @@ -0,0 +1,121 @@ +import com.sinch.sdk.SinchClient; +import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.ConversationRegion; +import com.sinch.sdk.models.SMSRegion; +import java.io.IOException; +import java.io.InputStream; +import java.util.Optional; +import java.util.Properties; +import java.util.logging.Logger; + +public class SinchClientHelper { + + private static final Logger LOGGER = Logger.getLogger(SinchClientHelper.class.getName()); + + private static final String SINCH_PROJECT_ID = "SINCH_PROJECT_ID"; + private static final String SINCH_KEY_ID = "SINCH_KEY_ID"; + private static final String SINCH_KEY_SECRET = "SINCH_KEY_SECRET"; + + private static final String APPLICATION_API_KEY = "APPLICATION_API_KEY"; + private static final String APPLICATION_API_SECRET = "APPLICATION_API_SECRET"; + + private static final String SMS_SERVICE_PLAN_ID = "SMS_SERVICE_PLAN_ID"; + private static final String SMS_SERVICE_PLAN_TOKEN = "SMS_SERVICE_PLAN_TOKEN"; + private static final String SMS_REGION = "SMS_REGION"; + + private static final String CONVERSATION_REGION = "CONVERSATION_REGION"; + + private static final String CONFIG_FILE = "config.properties"; + + public static SinchClient initSinchClient() { + + LOGGER.info("Initializing client"); + + Configuration configuration = getConfiguration(); + + return new SinchClient(configuration); + } + + private static Configuration getConfiguration() { + + Properties properties = loadProperties(); + + Configuration.Builder builder = Configuration.builder(); + + manageUnifiedCredentials(properties, builder); + manageApplicationCredentials(properties, builder); + manageConversationConfiguration(properties, builder); + manageSmsConfiguration(properties, builder); + + return builder.build(); + } + + private static Properties loadProperties() { + + Properties properties = new Properties(); + + try (InputStream input = + SinchClientHelper.class.getClassLoader().getResourceAsStream(CONFIG_FILE)) { + if (input != null) { + properties.load(input); + } else { + LOGGER.severe(String.format("'%s' file could not be loaded", CONFIG_FILE)); + } + } catch (IOException e) { + LOGGER.severe(String.format("Error loading properties from '%s'", CONFIG_FILE)); + } + + return properties; + } + + static void manageUnifiedCredentials(Properties properties, Configuration.Builder builder) { + + Optional projectId = getConfigValue(properties, SINCH_PROJECT_ID); + Optional keyId = getConfigValue(properties, SINCH_KEY_ID); + Optional keySecret = getConfigValue(properties, SINCH_KEY_SECRET); + + projectId.ifPresent(builder::setProjectId); + keyId.ifPresent(builder::setKeyId); + keySecret.ifPresent(builder::setKeySecret); + } + + private static void manageApplicationCredentials( + Properties properties, Configuration.Builder builder) { + + Optional verificationApiKey = getConfigValue(properties, APPLICATION_API_KEY); + Optional verificationApiSecret = getConfigValue(properties, APPLICATION_API_SECRET); + + verificationApiKey.ifPresent(builder::setApplicationKey); + verificationApiSecret.ifPresent(builder::setApplicationSecret); + } + + private static void manageConversationConfiguration( + Properties properties, Configuration.Builder builder) { + + Optional region = getConfigValue(properties, CONVERSATION_REGION); + + region.ifPresent(value -> builder.setConversationRegion(ConversationRegion.from(value))); + } + + private static void manageSmsConfiguration(Properties properties, Configuration.Builder builder) { + + Optional servicePlanId = getConfigValue(properties, SMS_SERVICE_PLAN_ID); + Optional servicePlanToken = getConfigValue(properties, SMS_SERVICE_PLAN_TOKEN); + Optional region = getConfigValue(properties, SMS_REGION); + + servicePlanId.ifPresent(builder::setSmsServicePlanId); + servicePlanToken.ifPresent(builder::setSmsApiToken); + region.ifPresent(value -> builder.setSmsRegion(SMSRegion.from(value))); + } + + private static Optional getConfigValue(Properties properties, String key) { + String value = null != System.getenv(key) ? System.getenv(key) : properties.getProperty(key); + + // empty value means setting not set + if (null != value && value.trim().isEmpty()) { + return Optional.empty(); + } + + return Optional.ofNullable(value); + } +} diff --git a/examples/client/src/main/java/conversation/ConversationQuickStart.java b/examples/client/src/main/java/conversation/ConversationQuickStart.java new file mode 100644 index 000000000..d3ecfa9c9 --- /dev/null +++ b/examples/client/src/main/java/conversation/ConversationQuickStart.java @@ -0,0 +1,18 @@ +package conversation; + +import com.sinch.sdk.domains.conversation.api.v1.ConversationService; +import java.util.logging.Logger; + +public class ConversationQuickStart { + + private static final Logger LOGGER = Logger.getLogger(ConversationQuickStart.class.getName()); + + private final ConversationService conversationService; + + public ConversationQuickStart(ConversationService conversationService) { + this.conversationService = conversationService; + + // Insert your application logic or business process here + LOGGER.info("Snippet execution"); + } +} diff --git a/examples/client/src/main/java/numbers/NumbersQuickStart.java b/examples/client/src/main/java/numbers/NumbersQuickStart.java new file mode 100644 index 000000000..54de68f5d --- /dev/null +++ b/examples/client/src/main/java/numbers/NumbersQuickStart.java @@ -0,0 +1,18 @@ +package numbers; + +import com.sinch.sdk.domains.numbers.api.v1.NumbersService; +import java.util.logging.Logger; + +public class NumbersQuickStart { + + private static final Logger LOGGER = Logger.getLogger(NumbersQuickStart.class.getName()); + + private final NumbersService numbersService; + + public NumbersQuickStart(NumbersService numbersService) { + this.numbersService = numbersService; + + // Insert your application logic or business process here + LOGGER.info("Snippet execution"); + } +} diff --git a/examples/client/src/main/java/sms/SmsQuickStart.java b/examples/client/src/main/java/sms/SmsQuickStart.java new file mode 100644 index 000000000..5d05bb178 --- /dev/null +++ b/examples/client/src/main/java/sms/SmsQuickStart.java @@ -0,0 +1,18 @@ +package sms; + +import com.sinch.sdk.domains.sms.api.v1.SMSService; +import java.util.logging.Logger; + +public class SmsQuickStart { + + private static final Logger LOGGER = Logger.getLogger(SmsQuickStart.class.getName()); + + private final SMSService smsService; + + public SmsQuickStart(SMSService smsService) { + this.smsService = smsService; + + // Insert your application logic or business process here + LOGGER.info("Snippet execution"); + } +} diff --git a/examples/client/src/main/java/verification/VerificationQuickStart.java b/examples/client/src/main/java/verification/VerificationQuickStart.java new file mode 100644 index 000000000..cdf06654f --- /dev/null +++ b/examples/client/src/main/java/verification/VerificationQuickStart.java @@ -0,0 +1,18 @@ +package verification; + +import com.sinch.sdk.domains.verification.api.v1.VerificationService; +import java.util.logging.Logger; + +public class VerificationQuickStart { + + private static final Logger LOGGER = Logger.getLogger(VerificationQuickStart.class.getName()); + + private final VerificationService verificationService; + + public VerificationQuickStart(VerificationService verificationService) { + this.verificationService = verificationService; + + // Insert your application logic or business process here + LOGGER.info("Snippet execution"); + } +} diff --git a/examples/client/src/main/java/voice/VoiceQuickStart.java b/examples/client/src/main/java/voice/VoiceQuickStart.java new file mode 100644 index 000000000..4aa1f82b5 --- /dev/null +++ b/examples/client/src/main/java/voice/VoiceQuickStart.java @@ -0,0 +1,18 @@ +package voice; + +import com.sinch.sdk.domains.voice.api.v1.VoiceService; +import java.util.logging.Logger; + +public class VoiceQuickStart { + + private static final Logger LOGGER = Logger.getLogger(VoiceQuickStart.class.getName()); + + private final VoiceService voiceService; + + public VoiceQuickStart(VoiceService voiceService) { + this.voiceService = voiceService; + + // Insert your application logic or business process here + LOGGER.info("Snippet execution"); + } +} diff --git a/examples/client/src/main/resources/config.properties b/examples/client/src/main/resources/config.properties new file mode 100644 index 000000000..50c967fb3 --- /dev/null +++ b/examples/client/src/main/resources/config.properties @@ -0,0 +1,25 @@ +# Java SDK domains supporting unified credentials +# - Numbers +# - SMS: US/EU are the only supported regions with unified credentials +# - Conversation +SINCH_PROJECT_ID = +SINCH_KEY_ID = +SINCH_KEY_SECRET = + +# Application related credentials, used by: +# - Verification +# - Voice +#APPLICATION_API_KEY = +#APPLICATION_API_SECRET = + +# SMS Service Plan ID related credentials +# if set, these credentials will be used and enable to use regions different of US/EU +#SMS_SERVICE_PLAN_ID = +#SMS_SERVICE_PLAN_TOKEN = + +# See https://github.com/sinch/sinch-sdk-java/blob/main/client/src/main/com/sinch/sdk/models/SMSRegion.java for full list of supported values but with servicePlanID +# valid values are "us" and "eu" +#SMS_REGION = us + +# See https://github.com/sinch/sinch-sdk-java/blob/main/client/src/main/com/sinch/sdk/models/ConversationRegion.java for list of supported values +#CONVERSATION_REGION = us diff --git a/examples/client/src/main/resources/logging.properties b/examples/client/src/main/resources/logging.properties new file mode 100644 index 000000000..5ed611e50 --- /dev/null +++ b/examples/client/src/main/resources/logging.properties @@ -0,0 +1,8 @@ + +handlers = java.util.logging.ConsoleHandler +java.util.logging.ConsoleHandler.level = INFO +com.sinch.level = INFO + +java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter +java.util.logging.SimpleFormatter.format=[%1$tF %1$tT] [%4$-7s %2$s] %5$s %n + diff --git a/examples/compile.sh b/examples/compile.sh index 7b868c724..b32876293 100755 --- a/examples/compile.sh +++ b/examples/compile.sh @@ -1,3 +1,11 @@ #!/bin/sh +SDK_VERSION=$(cd .. && mvn -q -Dexec.executable=echo -Dexec.args='${project.version}' --non-recursive exec:exec) + +export SDK_VERSION="${SDK_VERSION}" + (cd snippets && ./compile.sh) || exit 1 +(cd webhooks && ./compile.sh) || exit 1 +(cd client && mvn -Puse-version clean package) || exit 1 +(cd getting-started && ./compile.sh) || exit 1 +(cd tutorials && ./compile.sh) || exit 1 diff --git a/examples/getting-started/compile.sh b/examples/getting-started/compile.sh new file mode 100755 index 000000000..1a5bb5770 --- /dev/null +++ b/examples/getting-started/compile.sh @@ -0,0 +1,18 @@ +#!/bin/sh + +DIRECTORIES=" +conversation/send-text-message +numbers/rent-and-configure +numbers/rent-first-available-number +numbers/search-available +sms/send-sms-message +sms/respond-to-incoming-message +verification/user-verification-using-sms-pin +voice/respond-to-incoming-call +voice/make-a-call +" + +for DIRECTORY in $DIRECTORIES +do + (cd "$DIRECTORY" && echo "$PWD" && mvn -Puse-version clean package) || exit 1 +done diff --git a/examples/getting-started/conversation/send-text-message/README.md b/examples/getting-started/conversation/send-text-message/README.md new file mode 100644 index 000000000..62395832c --- /dev/null +++ b/examples/getting-started/conversation/send-text-message/README.md @@ -0,0 +1,5 @@ +# Sinch Getting Started: Send a Conversation Message (Java) + +Code is related to [Send a Conversation Message with the Sinch Java SDK](https://developers.sinch.com/docs/conversation/getting-started#4-send-the-message). + +See [Client template README](../../../client/README.md) for details about configuration and usage. diff --git a/examples/getting-started/conversation/send-text-message/pom.xml b/examples/getting-started/conversation/send-text-message/pom.xml new file mode 100644 index 000000000..ec116f9fa --- /dev/null +++ b/examples/getting-started/conversation/send-text-message/pom.xml @@ -0,0 +1,94 @@ + + + 4.0.0 + + my.company.com + sinch-java-sdk-client-application + 1.0-SNAPSHOT + jar + Sinch Java SDK Client Application + + + + use-version + + ${env.SDK_VERSION} + + + + + + [2.0.0,) + 8 + 8 + 3.13.0 + UTF-8 + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.6.0 + + + add-sources + generate-sources + + add-source + + + + src/main/java + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + Application + + + + + jar-with-dependencies + + + + + package + + single + + + + + + + + + + + com.sinch.sdk + sinch-sdk-java + ${sinch.sdk.java.version} + + + + org.slf4j + slf4j-jdk14 + 2.0.9 + + + + + diff --git a/examples/getting-started/conversation/send-text-message/src/main/java/Application.java b/examples/getting-started/conversation/send-text-message/src/main/java/Application.java new file mode 100644 index 000000000..431d9755f --- /dev/null +++ b/examples/getting-started/conversation/send-text-message/src/main/java/Application.java @@ -0,0 +1,42 @@ +import com.sinch.sdk.SinchClient; +import conversation.ConversationQuickStart; +import java.io.IOException; +import java.io.InputStream; +import java.util.logging.LogManager; +import java.util.logging.Logger; + +public abstract class Application { + + private static final String LOGGING_PROPERTIES_FILE = "logging.properties"; + private static final Logger LOGGER = initializeLogger(); + + public static void main(String[] args) { + try { + + SinchClient client = SinchClientHelper.initSinchClient(); + LOGGER.info("Application initiated. SinchClient ready."); + + ConversationQuickStart conversation = new ConversationQuickStart(client.conversation().v1()); + + } catch (Exception e) { + LOGGER.severe(String.format("Application failure: %s", e.getMessage())); + } + } + + static Logger initializeLogger() { + try (InputStream logConfigInputStream = + Application.class.getClassLoader().getResourceAsStream(LOGGING_PROPERTIES_FILE)) { + + if (logConfigInputStream != null) { + LogManager.getLogManager().readConfiguration(logConfigInputStream); + } else { + throw new RuntimeException( + String.format("The file '%s' couldn't be loaded.", LOGGING_PROPERTIES_FILE)); + } + + } catch (IOException e) { + throw new RuntimeException(e.getMessage()); + } + return Logger.getLogger(Application.class.getName()); + } +} diff --git a/examples/getting-started/conversation/send-text-message/src/main/java/SinchClientHelper.java b/examples/getting-started/conversation/send-text-message/src/main/java/SinchClientHelper.java new file mode 100644 index 000000000..fdc54f11b --- /dev/null +++ b/examples/getting-started/conversation/send-text-message/src/main/java/SinchClientHelper.java @@ -0,0 +1,90 @@ +import com.sinch.sdk.SinchClient; +import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.ConversationRegion; +import java.io.IOException; +import java.io.InputStream; +import java.util.Optional; +import java.util.Properties; +import java.util.logging.Logger; + +public class SinchClientHelper { + + private static final Logger LOGGER = Logger.getLogger(SinchClientHelper.class.getName()); + + private static final String SINCH_PROJECT_ID = "SINCH_PROJECT_ID"; + private static final String SINCH_KEY_ID = "SINCH_KEY_ID"; + private static final String SINCH_KEY_SECRET = "SINCH_KEY_SECRET"; + + private static final String CONVERSATION_REGION = "CONVERSATION_REGION"; + + private static final String CONFIG_FILE = "config.properties"; + + public static SinchClient initSinchClient() { + + LOGGER.info("Initializing client"); + + Configuration configuration = getConfiguration(); + + return new SinchClient(configuration); + } + + private static Configuration getConfiguration() { + + Properties properties = loadProperties(); + + Configuration.Builder builder = Configuration.builder(); + + manageUnifiedCredentials(properties, builder); + manageConversationConfiguration(properties, builder); + + return builder.build(); + } + + private static Properties loadProperties() { + + Properties properties = new Properties(); + + try (InputStream input = + SinchClientHelper.class.getClassLoader().getResourceAsStream(CONFIG_FILE)) { + if (input != null) { + properties.load(input); + } else { + LOGGER.severe(String.format("'%s' file could not be loaded", CONFIG_FILE)); + } + } catch (IOException e) { + LOGGER.severe(String.format("Error loading properties from '%s'", CONFIG_FILE)); + } + + return properties; + } + + static void manageUnifiedCredentials(Properties properties, Configuration.Builder builder) { + + Optional projectId = getConfigValue(properties, SINCH_PROJECT_ID); + Optional keyId = getConfigValue(properties, SINCH_KEY_ID); + Optional keySecret = getConfigValue(properties, SINCH_KEY_SECRET); + + projectId.ifPresent(builder::setProjectId); + keyId.ifPresent(builder::setKeyId); + keySecret.ifPresent(builder::setKeySecret); + } + + private static void manageConversationConfiguration( + Properties properties, Configuration.Builder builder) { + + Optional region = getConfigValue(properties, CONVERSATION_REGION); + + region.ifPresent(value -> builder.setConversationRegion(ConversationRegion.from(value))); + } + + private static Optional getConfigValue(Properties properties, String key) { + String value = null != System.getenv(key) ? System.getenv(key) : properties.getProperty(key); + + // empty value means setting not set + if (null != value && value.trim().isEmpty()) { + return Optional.empty(); + } + + return Optional.ofNullable(value); + } +} diff --git a/examples/getting-started/conversation/send-text-message/src/main/java/conversation/ConversationQuickStart.java b/examples/getting-started/conversation/send-text-message/src/main/java/conversation/ConversationQuickStart.java new file mode 100644 index 000000000..471ff928f --- /dev/null +++ b/examples/getting-started/conversation/send-text-message/src/main/java/conversation/ConversationQuickStart.java @@ -0,0 +1,15 @@ +package conversation; + +import com.sinch.sdk.domains.conversation.api.v1.ConversationService; + +public class ConversationQuickStart { + + private final ConversationService conversationService; + + public ConversationQuickStart(ConversationService conversationService) { + this.conversationService = conversationService; + + // Insert your application logic or business process here + Snippet.execute(this.conversationService); + } +} diff --git a/examples/getting-started/conversation/send-text-message/src/main/java/conversation/Snippet.java b/examples/getting-started/conversation/send-text-message/src/main/java/conversation/Snippet.java new file mode 100644 index 000000000..639e14c08 --- /dev/null +++ b/examples/getting-started/conversation/send-text-message/src/main/java/conversation/Snippet.java @@ -0,0 +1,55 @@ +package conversation; + +import com.sinch.sdk.domains.conversation.api.v1.ConversationService; +import com.sinch.sdk.domains.conversation.api.v1.MessagesService; +import com.sinch.sdk.domains.conversation.models.v1.ChannelRecipientIdentities; +import com.sinch.sdk.domains.conversation.models.v1.ChannelRecipientIdentity; +import com.sinch.sdk.domains.conversation.models.v1.ConversationChannel; +import com.sinch.sdk.domains.conversation.models.v1.messages.AppMessage; +import com.sinch.sdk.domains.conversation.models.v1.messages.request.SendMessageRequest; +import com.sinch.sdk.domains.conversation.models.v1.messages.response.SendMessageResponse; +import com.sinch.sdk.domains.conversation.models.v1.messages.types.text.TextMessage; +import java.util.Collections; +import java.util.logging.Logger; + +public class Snippet { + + private static final Logger LOGGER = Logger.getLogger(Snippet.class.getName()); + + static void execute(ConversationService conversationService) { + + MessagesService messagesService = conversationService.messages(); + + String appId = "CONVERSATION_APPLICATION_ID"; + String from = "SINCH_VIRTUAL_PHONE_NUMBER"; + String to = "RECIPIENT_PHONE_NUMBER"; + + String body = "This is a test Conversation message using the Sinch Java SDK."; + + ChannelRecipientIdentities recipients = + ChannelRecipientIdentities.of( + ChannelRecipientIdentity.builder() + .setChannel(ConversationChannel.SMS) + .setIdentity(to) + .build()); + + AppMessage message = + AppMessage.builder() + .setBody(TextMessage.builder().setText(body).build()) + .build(); + + SendMessageRequest request = + SendMessageRequest.builder() + .setAppId(appId) + .setRecipient(recipients) + .setMessage(message) + .setChannelProperties(Collections.singletonMap("SMS_SENDER", from)) + .build(); + + LOGGER.info("Sending SMS Text using Conversation API"); + + SendMessageResponse value = messagesService.sendMessage(request); + + LOGGER.info("Response: " + value); + } +} diff --git a/examples/getting-started/conversation/send-text-message/src/main/resources/config.properties b/examples/getting-started/conversation/send-text-message/src/main/resources/config.properties new file mode 100644 index 000000000..ea97bca13 --- /dev/null +++ b/examples/getting-started/conversation/send-text-message/src/main/resources/config.properties @@ -0,0 +1,7 @@ +# Required credentials for using the Conversation API +SINCH_PROJECT_ID= +SINCH_KEY_ID= +SINCH_KEY_SECRET= + +# See https://github.com/sinch/sinch-sdk-java/blob/main/client/src/main/com/sinch/sdk/models/ConversationRegion.java for list of supported values +#CONVERSATION_REGION = us \ No newline at end of file diff --git a/examples/getting-started/conversation/send-text-message/src/main/resources/logging.properties b/examples/getting-started/conversation/send-text-message/src/main/resources/logging.properties new file mode 100644 index 000000000..5ed611e50 --- /dev/null +++ b/examples/getting-started/conversation/send-text-message/src/main/resources/logging.properties @@ -0,0 +1,8 @@ + +handlers = java.util.logging.ConsoleHandler +java.util.logging.ConsoleHandler.level = INFO +com.sinch.level = INFO + +java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter +java.util.logging.SimpleFormatter.format=[%1$tF %1$tT] [%4$-7s %2$s] %5$s %n + diff --git a/examples/getting-started/numbers/rent-and-configure/README.md b/examples/getting-started/numbers/rent-and-configure/README.md new file mode 100644 index 000000000..a38b10d99 --- /dev/null +++ b/examples/getting-started/numbers/rent-and-configure/README.md @@ -0,0 +1,5 @@ +# Sinch Getting Started: Rent and Configure a Virtual Number (Java) + +Code is related to [Rent and configure your virtual number using Java](https://developers.sinch.com/docs/numbers/getting-started). + +See [Client template README](../../../client/README.md) for details about configuration and usage. diff --git a/examples/getting-started/numbers/rent-and-configure/pom.xml b/examples/getting-started/numbers/rent-and-configure/pom.xml new file mode 100644 index 000000000..ec116f9fa --- /dev/null +++ b/examples/getting-started/numbers/rent-and-configure/pom.xml @@ -0,0 +1,94 @@ + + + 4.0.0 + + my.company.com + sinch-java-sdk-client-application + 1.0-SNAPSHOT + jar + Sinch Java SDK Client Application + + + + use-version + + ${env.SDK_VERSION} + + + + + + [2.0.0,) + 8 + 8 + 3.13.0 + UTF-8 + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.6.0 + + + add-sources + generate-sources + + add-source + + + + src/main/java + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + Application + + + + + jar-with-dependencies + + + + + package + + single + + + + + + + + + + + com.sinch.sdk + sinch-sdk-java + ${sinch.sdk.java.version} + + + + org.slf4j + slf4j-jdk14 + 2.0.9 + + + + + diff --git a/examples/getting-started/numbers/rent-and-configure/src/main/java/Application.java b/examples/getting-started/numbers/rent-and-configure/src/main/java/Application.java new file mode 100644 index 000000000..f029b86fe --- /dev/null +++ b/examples/getting-started/numbers/rent-and-configure/src/main/java/Application.java @@ -0,0 +1,42 @@ +import com.sinch.sdk.SinchClient; +import java.io.IOException; +import java.io.InputStream; +import java.util.logging.LogManager; +import java.util.logging.Logger; +import numbers.NumbersQuickStart; + +public abstract class Application { + + private static final String LOGGING_PROPERTIES_FILE = "logging.properties"; + private static final Logger LOGGER = initializeLogger(); + + public static void main(String[] args) { + try { + + SinchClient client = SinchClientHelper.initSinchClient(); + LOGGER.info("Application initiated. SinchClient ready."); + + NumbersQuickStart numbers = new NumbersQuickStart(client.numbers().v1()); + + } catch (Exception e) { + LOGGER.severe(String.format("Application failure: %s", e.getMessage())); + } + } + + static Logger initializeLogger() { + try (InputStream logConfigInputStream = + Application.class.getClassLoader().getResourceAsStream(LOGGING_PROPERTIES_FILE)) { + + if (logConfigInputStream != null) { + LogManager.getLogManager().readConfiguration(logConfigInputStream); + } else { + throw new RuntimeException( + String.format("The file '%s' couldn't be loaded.", LOGGING_PROPERTIES_FILE)); + } + + } catch (IOException e) { + throw new RuntimeException(e.getMessage()); + } + return Logger.getLogger(Application.class.getName()); + } +} diff --git a/examples/getting-started/numbers/rent-and-configure/src/main/java/SinchClientHelper.java b/examples/getting-started/numbers/rent-and-configure/src/main/java/SinchClientHelper.java new file mode 100644 index 000000000..b454c5077 --- /dev/null +++ b/examples/getting-started/numbers/rent-and-configure/src/main/java/SinchClientHelper.java @@ -0,0 +1,78 @@ +import com.sinch.sdk.SinchClient; +import com.sinch.sdk.models.Configuration; +import java.io.IOException; +import java.io.InputStream; +import java.util.Optional; +import java.util.Properties; +import java.util.logging.Logger; + +public class SinchClientHelper { + + private static final Logger LOGGER = Logger.getLogger(SinchClientHelper.class.getName()); + + private static final String SINCH_PROJECT_ID = "SINCH_PROJECT_ID"; + private static final String SINCH_KEY_ID = "SINCH_KEY_ID"; + private static final String SINCH_KEY_SECRET = "SINCH_KEY_SECRET"; + + private static final String CONFIG_FILE = "config.properties"; + + public static SinchClient initSinchClient() { + + LOGGER.info("Initializing client"); + + Configuration configuration = getConfiguration(); + + return new SinchClient(configuration); + } + + private static Configuration getConfiguration() { + + Properties properties = loadProperties(); + + Configuration.Builder builder = Configuration.builder(); + + manageUnifiedCredentials(properties, builder); + + return builder.build(); + } + + private static Properties loadProperties() { + + Properties properties = new Properties(); + + try (InputStream input = + SinchClientHelper.class.getClassLoader().getResourceAsStream(CONFIG_FILE)) { + if (input != null) { + properties.load(input); + } else { + LOGGER.severe(String.format("'%s' file could not be loaded", CONFIG_FILE)); + } + } catch (IOException e) { + LOGGER.severe(String.format("Error loading properties from '%s'", CONFIG_FILE)); + } + + return properties; + } + + static void manageUnifiedCredentials(Properties properties, Configuration.Builder builder) { + + Optional projectId = getConfigValue(properties, SINCH_PROJECT_ID); + Optional keyId = getConfigValue(properties, SINCH_KEY_ID); + Optional keySecret = getConfigValue(properties, SINCH_KEY_SECRET); + + projectId.ifPresent(builder::setProjectId); + keyId.ifPresent(builder::setKeyId); + keySecret.ifPresent(builder::setKeySecret); + } + + private static Optional getConfigValue(Properties properties, String key) { + String value = null != System.getenv(key) ? System.getenv(key) : properties.getProperty(key); + + // empty value means setting not set + if (null != value && value.trim().isEmpty()) { + return Optional.empty(); + } + + return Optional.ofNullable(value); + } +} diff --git a/examples/getting-started/numbers/rent-and-configure/src/main/java/numbers/NumbersQuickStart.java b/examples/getting-started/numbers/rent-and-configure/src/main/java/numbers/NumbersQuickStart.java new file mode 100644 index 000000000..f688683a8 --- /dev/null +++ b/examples/getting-started/numbers/rent-and-configure/src/main/java/numbers/NumbersQuickStart.java @@ -0,0 +1,15 @@ +package numbers; + +import com.sinch.sdk.domains.numbers.api.v1.NumbersService; + +public class NumbersQuickStart { + + private final NumbersService numbersService; + + public NumbersQuickStart(NumbersService numbersService) { + this.numbersService = numbersService; + + // Insert your application logic or business process here + Snippet.execute(this.numbersService); + } +} diff --git a/examples/getting-started/numbers/rent-and-configure/src/main/java/numbers/Snippet.java b/examples/getting-started/numbers/rent-and-configure/src/main/java/numbers/Snippet.java new file mode 100644 index 000000000..5079dec0b --- /dev/null +++ b/examples/getting-started/numbers/rent-and-configure/src/main/java/numbers/Snippet.java @@ -0,0 +1,36 @@ +package numbers; + +import com.sinch.sdk.domains.numbers.api.v1.NumbersService; +import com.sinch.sdk.domains.numbers.models.v1.ActiveNumber; +import com.sinch.sdk.domains.numbers.models.v1.SmsConfiguration; +import com.sinch.sdk.domains.numbers.models.v1.request.AvailableNumberRentRequest; +import java.util.logging.Logger; + +public class Snippet { + + private static final Logger LOGGER = Logger.getLogger(Snippet.class.getName()); + + static void execute(NumbersService numbersService) { + + // Available numbers list can be retrieved by using list() function from available service, see: + // https://developers.sinch.com/docs/numbers/getting-started + String phoneNumberToBeRented = "AVAILABLE_PHONE_NUMBER_TO_BE_RENTED"; + String servicePlanIdToAssociateWithTheNumber = "MY_SERVICE_PLAN_ID"; + + SmsConfiguration smsConfiguration = + SmsConfiguration.builder().setServicePlanId(servicePlanIdToAssociateWithTheNumber).build(); + + LOGGER.info( + String.format( + "Sending request to rent the virtual number: '%s' and configure it with the" + + " pre-configured service plan id '%s' to use the SMS capability", + phoneNumberToBeRented, servicePlanIdToAssociateWithTheNumber)); + + AvailableNumberRentRequest rentRequest = + AvailableNumberRentRequest.builder().setSmsConfiguration(smsConfiguration).build(); + + ActiveNumber response = numbersService.rent(phoneNumberToBeRented, rentRequest); + + LOGGER.info(String.format("Rented number: %s", response)); + } +} diff --git a/examples/getting-started/numbers/rent-and-configure/src/main/resources/config.properties b/examples/getting-started/numbers/rent-and-configure/src/main/resources/config.properties new file mode 100644 index 000000000..2ff29a19e --- /dev/null +++ b/examples/getting-started/numbers/rent-and-configure/src/main/resources/config.properties @@ -0,0 +1,4 @@ +# Required credentials for using the Numbers API +SINCH_PROJECT_ID= +SINCH_KEY_ID= +SINCH_KEY_SECRET= diff --git a/examples/getting-started/numbers/rent-and-configure/src/main/resources/logging.properties b/examples/getting-started/numbers/rent-and-configure/src/main/resources/logging.properties new file mode 100644 index 000000000..5ed611e50 --- /dev/null +++ b/examples/getting-started/numbers/rent-and-configure/src/main/resources/logging.properties @@ -0,0 +1,8 @@ + +handlers = java.util.logging.ConsoleHandler +java.util.logging.ConsoleHandler.level = INFO +com.sinch.level = INFO + +java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter +java.util.logging.SimpleFormatter.format=[%1$tF %1$tT] [%4$-7s %2$s] %5$s %n + diff --git a/examples/getting-started/numbers/rent-first-available-number/README.md b/examples/getting-started/numbers/rent-first-available-number/README.md new file mode 100644 index 000000000..eda92c79d --- /dev/null +++ b/examples/getting-started/numbers/rent-first-available-number/README.md @@ -0,0 +1,5 @@ +# Sinch Getting Started: Rent First Available Number (Java) + +Code is related to [Rent the first available number using the Java SDK](https://developers.sinch.com/docs/numbers/getting-started). + +See [Client template README](../../../client/README.md) for details about configuration and usage. diff --git a/examples/getting-started/numbers/rent-first-available-number/pom.xml b/examples/getting-started/numbers/rent-first-available-number/pom.xml new file mode 100644 index 000000000..ec116f9fa --- /dev/null +++ b/examples/getting-started/numbers/rent-first-available-number/pom.xml @@ -0,0 +1,94 @@ + + + 4.0.0 + + my.company.com + sinch-java-sdk-client-application + 1.0-SNAPSHOT + jar + Sinch Java SDK Client Application + + + + use-version + + ${env.SDK_VERSION} + + + + + + [2.0.0,) + 8 + 8 + 3.13.0 + UTF-8 + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.6.0 + + + add-sources + generate-sources + + add-source + + + + src/main/java + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + Application + + + + + jar-with-dependencies + + + + + package + + single + + + + + + + + + + + com.sinch.sdk + sinch-sdk-java + ${sinch.sdk.java.version} + + + + org.slf4j + slf4j-jdk14 + 2.0.9 + + + + + diff --git a/examples/getting-started/numbers/rent-first-available-number/src/main/java/Application.java b/examples/getting-started/numbers/rent-first-available-number/src/main/java/Application.java new file mode 100644 index 000000000..f029b86fe --- /dev/null +++ b/examples/getting-started/numbers/rent-first-available-number/src/main/java/Application.java @@ -0,0 +1,42 @@ +import com.sinch.sdk.SinchClient; +import java.io.IOException; +import java.io.InputStream; +import java.util.logging.LogManager; +import java.util.logging.Logger; +import numbers.NumbersQuickStart; + +public abstract class Application { + + private static final String LOGGING_PROPERTIES_FILE = "logging.properties"; + private static final Logger LOGGER = initializeLogger(); + + public static void main(String[] args) { + try { + + SinchClient client = SinchClientHelper.initSinchClient(); + LOGGER.info("Application initiated. SinchClient ready."); + + NumbersQuickStart numbers = new NumbersQuickStart(client.numbers().v1()); + + } catch (Exception e) { + LOGGER.severe(String.format("Application failure: %s", e.getMessage())); + } + } + + static Logger initializeLogger() { + try (InputStream logConfigInputStream = + Application.class.getClassLoader().getResourceAsStream(LOGGING_PROPERTIES_FILE)) { + + if (logConfigInputStream != null) { + LogManager.getLogManager().readConfiguration(logConfigInputStream); + } else { + throw new RuntimeException( + String.format("The file '%s' couldn't be loaded.", LOGGING_PROPERTIES_FILE)); + } + + } catch (IOException e) { + throw new RuntimeException(e.getMessage()); + } + return Logger.getLogger(Application.class.getName()); + } +} diff --git a/examples/getting-started/numbers/rent-first-available-number/src/main/java/SinchClientHelper.java b/examples/getting-started/numbers/rent-first-available-number/src/main/java/SinchClientHelper.java new file mode 100644 index 000000000..b454c5077 --- /dev/null +++ b/examples/getting-started/numbers/rent-first-available-number/src/main/java/SinchClientHelper.java @@ -0,0 +1,78 @@ +import com.sinch.sdk.SinchClient; +import com.sinch.sdk.models.Configuration; +import java.io.IOException; +import java.io.InputStream; +import java.util.Optional; +import java.util.Properties; +import java.util.logging.Logger; + +public class SinchClientHelper { + + private static final Logger LOGGER = Logger.getLogger(SinchClientHelper.class.getName()); + + private static final String SINCH_PROJECT_ID = "SINCH_PROJECT_ID"; + private static final String SINCH_KEY_ID = "SINCH_KEY_ID"; + private static final String SINCH_KEY_SECRET = "SINCH_KEY_SECRET"; + + private static final String CONFIG_FILE = "config.properties"; + + public static SinchClient initSinchClient() { + + LOGGER.info("Initializing client"); + + Configuration configuration = getConfiguration(); + + return new SinchClient(configuration); + } + + private static Configuration getConfiguration() { + + Properties properties = loadProperties(); + + Configuration.Builder builder = Configuration.builder(); + + manageUnifiedCredentials(properties, builder); + + return builder.build(); + } + + private static Properties loadProperties() { + + Properties properties = new Properties(); + + try (InputStream input = + SinchClientHelper.class.getClassLoader().getResourceAsStream(CONFIG_FILE)) { + if (input != null) { + properties.load(input); + } else { + LOGGER.severe(String.format("'%s' file could not be loaded", CONFIG_FILE)); + } + } catch (IOException e) { + LOGGER.severe(String.format("Error loading properties from '%s'", CONFIG_FILE)); + } + + return properties; + } + + static void manageUnifiedCredentials(Properties properties, Configuration.Builder builder) { + + Optional projectId = getConfigValue(properties, SINCH_PROJECT_ID); + Optional keyId = getConfigValue(properties, SINCH_KEY_ID); + Optional keySecret = getConfigValue(properties, SINCH_KEY_SECRET); + + projectId.ifPresent(builder::setProjectId); + keyId.ifPresent(builder::setKeyId); + keySecret.ifPresent(builder::setKeySecret); + } + + private static Optional getConfigValue(Properties properties, String key) { + String value = null != System.getenv(key) ? System.getenv(key) : properties.getProperty(key); + + // empty value means setting not set + if (null != value && value.trim().isEmpty()) { + return Optional.empty(); + } + + return Optional.ofNullable(value); + } +} diff --git a/examples/getting-started/numbers/rent-first-available-number/src/main/java/numbers/NumbersQuickStart.java b/examples/getting-started/numbers/rent-first-available-number/src/main/java/numbers/NumbersQuickStart.java new file mode 100644 index 000000000..f688683a8 --- /dev/null +++ b/examples/getting-started/numbers/rent-first-available-number/src/main/java/numbers/NumbersQuickStart.java @@ -0,0 +1,15 @@ +package numbers; + +import com.sinch.sdk.domains.numbers.api.v1.NumbersService; + +public class NumbersQuickStart { + + private final NumbersService numbersService; + + public NumbersQuickStart(NumbersService numbersService) { + this.numbersService = numbersService; + + // Insert your application logic or business process here + Snippet.execute(this.numbersService); + } +} diff --git a/examples/getting-started/numbers/rent-first-available-number/src/main/java/numbers/Snippet.java b/examples/getting-started/numbers/rent-first-available-number/src/main/java/numbers/Snippet.java new file mode 100644 index 000000000..67fe1e67a --- /dev/null +++ b/examples/getting-started/numbers/rent-first-available-number/src/main/java/numbers/Snippet.java @@ -0,0 +1,44 @@ +package numbers; + +import com.sinch.sdk.domains.numbers.api.v1.NumbersService; +import com.sinch.sdk.domains.numbers.models.v1.ActiveNumber; +import com.sinch.sdk.domains.numbers.models.v1.Capability; +import com.sinch.sdk.domains.numbers.models.v1.NumberType; +import com.sinch.sdk.domains.numbers.models.v1.SmsConfiguration; +import com.sinch.sdk.domains.numbers.models.v1.request.AvailableNumberRentAnyRequest; +import java.util.Collections; +import java.util.logging.Logger; + +public class Snippet { + + private static final Logger LOGGER = Logger.getLogger(Snippet.class.getName()); + + static void execute(NumbersService numbersService) { + + String servicePlanIdToAssociateWithTheNumber = "MY_SERVICE_PLAN_ID"; + String regionCode = "MY_REGION_CODE"; + + Capability capability = Capability.SMS; + NumberType numberType = NumberType.LOCAL; + + LOGGER.info( + String.format( + "Sending request to rent the first available number and configure it with the" + + " pre-configured service plan id '%s' to use the SMS capability", + servicePlanIdToAssociateWithTheNumber)); + + ActiveNumber response = + numbersService.rentAny( + AvailableNumberRentAnyRequest.builder() + .setCapabilities(Collections.singletonList(capability)) + .setType(numberType) + .setRegionCode(regionCode) + .setSmsConfiguration( + SmsConfiguration.builder() + .setServicePlanId(servicePlanIdToAssociateWithTheNumber) + .build()) + .build()); + + LOGGER.info(String.format("Rented number: %s", response)); + } +} diff --git a/examples/getting-started/numbers/rent-first-available-number/src/main/resources/config.properties b/examples/getting-started/numbers/rent-first-available-number/src/main/resources/config.properties new file mode 100644 index 000000000..2ff29a19e --- /dev/null +++ b/examples/getting-started/numbers/rent-first-available-number/src/main/resources/config.properties @@ -0,0 +1,4 @@ +# Required credentials for using the Numbers API +SINCH_PROJECT_ID= +SINCH_KEY_ID= +SINCH_KEY_SECRET= diff --git a/examples/getting-started/numbers/rent-first-available-number/src/main/resources/logging.properties b/examples/getting-started/numbers/rent-first-available-number/src/main/resources/logging.properties new file mode 100644 index 000000000..5ed611e50 --- /dev/null +++ b/examples/getting-started/numbers/rent-first-available-number/src/main/resources/logging.properties @@ -0,0 +1,8 @@ + +handlers = java.util.logging.ConsoleHandler +java.util.logging.ConsoleHandler.level = INFO +com.sinch.level = INFO + +java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter +java.util.logging.SimpleFormatter.format=[%1$tF %1$tT] [%4$-7s %2$s] %5$s %n + diff --git a/examples/getting-started/numbers/search-available/README.md b/examples/getting-started/numbers/search-available/README.md new file mode 100644 index 000000000..e1b15c4df --- /dev/null +++ b/examples/getting-started/numbers/search-available/README.md @@ -0,0 +1,5 @@ +# Sinch Getting Started: Search for Virtual Number (Java) + +Code is related to [Search for virtual number using the Java SDK](https://developers.sinch.com/docs/numbers/getting-started). + +See [Client template README](../../../client/README.md) for details about configuration and usage. diff --git a/examples/getting-started/numbers/search-available/pom.xml b/examples/getting-started/numbers/search-available/pom.xml new file mode 100644 index 000000000..ec116f9fa --- /dev/null +++ b/examples/getting-started/numbers/search-available/pom.xml @@ -0,0 +1,94 @@ + + + 4.0.0 + + my.company.com + sinch-java-sdk-client-application + 1.0-SNAPSHOT + jar + Sinch Java SDK Client Application + + + + use-version + + ${env.SDK_VERSION} + + + + + + [2.0.0,) + 8 + 8 + 3.13.0 + UTF-8 + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.6.0 + + + add-sources + generate-sources + + add-source + + + + src/main/java + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + Application + + + + + jar-with-dependencies + + + + + package + + single + + + + + + + + + + + com.sinch.sdk + sinch-sdk-java + ${sinch.sdk.java.version} + + + + org.slf4j + slf4j-jdk14 + 2.0.9 + + + + + diff --git a/examples/getting-started/numbers/search-available/src/main/java/Application.java b/examples/getting-started/numbers/search-available/src/main/java/Application.java new file mode 100644 index 000000000..f029b86fe --- /dev/null +++ b/examples/getting-started/numbers/search-available/src/main/java/Application.java @@ -0,0 +1,42 @@ +import com.sinch.sdk.SinchClient; +import java.io.IOException; +import java.io.InputStream; +import java.util.logging.LogManager; +import java.util.logging.Logger; +import numbers.NumbersQuickStart; + +public abstract class Application { + + private static final String LOGGING_PROPERTIES_FILE = "logging.properties"; + private static final Logger LOGGER = initializeLogger(); + + public static void main(String[] args) { + try { + + SinchClient client = SinchClientHelper.initSinchClient(); + LOGGER.info("Application initiated. SinchClient ready."); + + NumbersQuickStart numbers = new NumbersQuickStart(client.numbers().v1()); + + } catch (Exception e) { + LOGGER.severe(String.format("Application failure: %s", e.getMessage())); + } + } + + static Logger initializeLogger() { + try (InputStream logConfigInputStream = + Application.class.getClassLoader().getResourceAsStream(LOGGING_PROPERTIES_FILE)) { + + if (logConfigInputStream != null) { + LogManager.getLogManager().readConfiguration(logConfigInputStream); + } else { + throw new RuntimeException( + String.format("The file '%s' couldn't be loaded.", LOGGING_PROPERTIES_FILE)); + } + + } catch (IOException e) { + throw new RuntimeException(e.getMessage()); + } + return Logger.getLogger(Application.class.getName()); + } +} diff --git a/examples/getting-started/numbers/search-available/src/main/java/SinchClientHelper.java b/examples/getting-started/numbers/search-available/src/main/java/SinchClientHelper.java new file mode 100644 index 000000000..b454c5077 --- /dev/null +++ b/examples/getting-started/numbers/search-available/src/main/java/SinchClientHelper.java @@ -0,0 +1,78 @@ +import com.sinch.sdk.SinchClient; +import com.sinch.sdk.models.Configuration; +import java.io.IOException; +import java.io.InputStream; +import java.util.Optional; +import java.util.Properties; +import java.util.logging.Logger; + +public class SinchClientHelper { + + private static final Logger LOGGER = Logger.getLogger(SinchClientHelper.class.getName()); + + private static final String SINCH_PROJECT_ID = "SINCH_PROJECT_ID"; + private static final String SINCH_KEY_ID = "SINCH_KEY_ID"; + private static final String SINCH_KEY_SECRET = "SINCH_KEY_SECRET"; + + private static final String CONFIG_FILE = "config.properties"; + + public static SinchClient initSinchClient() { + + LOGGER.info("Initializing client"); + + Configuration configuration = getConfiguration(); + + return new SinchClient(configuration); + } + + private static Configuration getConfiguration() { + + Properties properties = loadProperties(); + + Configuration.Builder builder = Configuration.builder(); + + manageUnifiedCredentials(properties, builder); + + return builder.build(); + } + + private static Properties loadProperties() { + + Properties properties = new Properties(); + + try (InputStream input = + SinchClientHelper.class.getClassLoader().getResourceAsStream(CONFIG_FILE)) { + if (input != null) { + properties.load(input); + } else { + LOGGER.severe(String.format("'%s' file could not be loaded", CONFIG_FILE)); + } + } catch (IOException e) { + LOGGER.severe(String.format("Error loading properties from '%s'", CONFIG_FILE)); + } + + return properties; + } + + static void manageUnifiedCredentials(Properties properties, Configuration.Builder builder) { + + Optional projectId = getConfigValue(properties, SINCH_PROJECT_ID); + Optional keyId = getConfigValue(properties, SINCH_KEY_ID); + Optional keySecret = getConfigValue(properties, SINCH_KEY_SECRET); + + projectId.ifPresent(builder::setProjectId); + keyId.ifPresent(builder::setKeyId); + keySecret.ifPresent(builder::setKeySecret); + } + + private static Optional getConfigValue(Properties properties, String key) { + String value = null != System.getenv(key) ? System.getenv(key) : properties.getProperty(key); + + // empty value means setting not set + if (null != value && value.trim().isEmpty()) { + return Optional.empty(); + } + + return Optional.ofNullable(value); + } +} diff --git a/examples/getting-started/numbers/search-available/src/main/java/numbers/NumbersQuickStart.java b/examples/getting-started/numbers/search-available/src/main/java/numbers/NumbersQuickStart.java new file mode 100644 index 000000000..f688683a8 --- /dev/null +++ b/examples/getting-started/numbers/search-available/src/main/java/numbers/NumbersQuickStart.java @@ -0,0 +1,15 @@ +package numbers; + +import com.sinch.sdk.domains.numbers.api.v1.NumbersService; + +public class NumbersQuickStart { + + private final NumbersService numbersService; + + public NumbersQuickStart(NumbersService numbersService) { + this.numbersService = numbersService; + + // Insert your application logic or business process here + Snippet.execute(this.numbersService); + } +} diff --git a/examples/getting-started/numbers/search-available/src/main/java/numbers/Snippet.java b/examples/getting-started/numbers/search-available/src/main/java/numbers/Snippet.java new file mode 100644 index 000000000..1da9e2ebb --- /dev/null +++ b/examples/getting-started/numbers/search-available/src/main/java/numbers/Snippet.java @@ -0,0 +1,34 @@ +package numbers; + +import com.sinch.sdk.domains.numbers.api.v1.NumbersService; +import com.sinch.sdk.domains.numbers.models.v1.NumberType; +import com.sinch.sdk.domains.numbers.models.v1.request.AvailableNumbersListQueryParameters; +import com.sinch.sdk.domains.numbers.models.v1.response.AvailableNumbersListResponse; +import java.util.logging.Logger; + +public class Snippet { + + private static final Logger LOGGER = Logger.getLogger(Snippet.class.getName()); + + static void execute(NumbersService numbersService) { + + String regionCode = "US"; + NumberType type = NumberType.LOCAL; + + AvailableNumbersListQueryParameters parameters = + AvailableNumbersListQueryParameters.builder() + .setRegionCode(regionCode) + .setType(type) + .build(); + + LOGGER.info( + String.format("Listing available number type '%s' for region '%s'", type, regionCode)); + + AvailableNumbersListResponse response = numbersService.searchForAvailableNumbers(parameters); + + response + .iterator() + .forEachRemaining( + number -> LOGGER.info(String.format("Available number details: %s", number))); + } +} diff --git a/examples/getting-started/numbers/search-available/src/main/resources/config.properties b/examples/getting-started/numbers/search-available/src/main/resources/config.properties new file mode 100644 index 000000000..2ff29a19e --- /dev/null +++ b/examples/getting-started/numbers/search-available/src/main/resources/config.properties @@ -0,0 +1,4 @@ +# Required credentials for using the Numbers API +SINCH_PROJECT_ID= +SINCH_KEY_ID= +SINCH_KEY_SECRET= diff --git a/examples/getting-started/numbers/search-available/src/main/resources/logging.properties b/examples/getting-started/numbers/search-available/src/main/resources/logging.properties new file mode 100644 index 000000000..5ed611e50 --- /dev/null +++ b/examples/getting-started/numbers/search-available/src/main/resources/logging.properties @@ -0,0 +1,8 @@ + +handlers = java.util.logging.ConsoleHandler +java.util.logging.ConsoleHandler.level = INFO +com.sinch.level = INFO + +java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter +java.util.logging.SimpleFormatter.format=[%1$tF %1$tT] [%4$-7s %2$s] %5$s %n + diff --git a/examples/getting-started/sms/respond-to-incoming-message/README.md b/examples/getting-started/sms/respond-to-incoming-message/README.md new file mode 100644 index 000000000..44bde99b9 --- /dev/null +++ b/examples/getting-started/sms/respond-to-incoming-message/README.md @@ -0,0 +1,5 @@ +# Sinch Getting Started: Respond to Incoming SMS Message (Java) + +Code is related to [Receive an SMS Message with Java](https://developers.sinch.com/docs/sms/getting-started/java/receive-sms-sdk). + +See [Server template README](../../../webhooks/README.md) for details about configuration and usage. diff --git a/examples/getting-started/sms/respond-to-incoming-message/pom.xml b/examples/getting-started/sms/respond-to-incoming-message/pom.xml new file mode 100644 index 000000000..9876b452f --- /dev/null +++ b/examples/getting-started/sms/respond-to-incoming-message/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 3.2.5 + + + + my.company.com + sinch-java-sdk-server-application + 0.0.1-SNAPSHOT + Sinch Java SDK Server Application + + + + use-version + + ${env.SDK_VERSION} + + + + + + [2.0.0,) + 21 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-web + + + + com.sinch.sdk + sinch-sdk-java + ${sinch.sdk.java.version} + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/examples/getting-started/sms/respond-to-incoming-message/src/main/java/com/mycompany/app/Application.java b/examples/getting-started/sms/respond-to-incoming-message/src/main/java/com/mycompany/app/Application.java new file mode 100644 index 000000000..03b399f0f --- /dev/null +++ b/examples/getting-started/sms/respond-to-incoming-message/src/main/java/com/mycompany/app/Application.java @@ -0,0 +1,12 @@ +package com.mycompany.app; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/examples/getting-started/sms/respond-to-incoming-message/src/main/java/com/mycompany/app/Config.java b/examples/getting-started/sms/respond-to-incoming-message/src/main/java/com/mycompany/app/Config.java new file mode 100644 index 000000000..e0404a9cb --- /dev/null +++ b/examples/getting-started/sms/respond-to-incoming-message/src/main/java/com/mycompany/app/Config.java @@ -0,0 +1,51 @@ +package com.mycompany.app; + +import com.sinch.sdk.SinchClient; +import com.sinch.sdk.core.utils.StringUtil; +import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.SMSRegion; +import java.util.logging.Logger; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; + +@org.springframework.context.annotation.Configuration +public class Config { + + private static final Logger LOGGER = Logger.getLogger(Config.class.getName()); + + @Value("${credentials.project-id: }") + String projectId; + + @Value("${credentials.key-id: }") + String keyId; + + @Value("${credentials.key-secret: }") + String keySecret; + + @Value("${sms.region: }") + String smsRegion; + + @Bean + public SinchClient sinchClient() { + + Configuration.Builder builder = Configuration.builder(); + + if (!StringUtil.isEmpty(projectId)) { + builder.setProjectId(projectId); + } + + if (!StringUtil.isEmpty(keyId)) { + builder.setKeyId(keyId); + } + if (!StringUtil.isEmpty(keySecret)) { + builder.setKeySecret(keySecret); + } + + if (!StringUtil.isEmpty(smsRegion)) { + builder.setSmsRegion(SMSRegion.from(smsRegion)); + LOGGER.info(String.format("SMS region: '%s'", smsRegion)); + } + + return new SinchClient(builder.build()); + } +} diff --git a/examples/getting-started/sms/respond-to-incoming-message/src/main/java/com/mycompany/app/sms/Controller.java b/examples/getting-started/sms/respond-to-incoming-message/src/main/java/com/mycompany/app/sms/Controller.java new file mode 100644 index 000000000..0892d9399 --- /dev/null +++ b/examples/getting-started/sms/respond-to-incoming-message/src/main/java/com/mycompany/app/sms/Controller.java @@ -0,0 +1,75 @@ +package com.mycompany.app.sms; + +import com.sinch.sdk.SinchClient; +import com.sinch.sdk.domains.sms.api.v1.WebHooksService; +import com.sinch.sdk.domains.sms.models.v1.inbounds.TextMessage; +import com.sinch.sdk.domains.sms.models.v1.webhooks.SmsEvent; +import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +@RestController("SMS") +public class Controller { + + private final SinchClient sinchClient; + private final ServerBusinessLogic webhooksBusinessLogic; + + @Value("${sms.webhooks.secret: }") + private String webhooksSecret; + + @Autowired + public Controller(SinchClient sinchClient, ServerBusinessLogic webhooksBusinessLogic) { + this.sinchClient = sinchClient; + this.webhooksBusinessLogic = webhooksBusinessLogic; + } + + @PostMapping( + value = "/SmsEvent", + consumes = MediaType.APPLICATION_JSON_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity smsDeliveryEvent( + @RequestHeader Map headers, @RequestBody String body) { + + WebHooksService webhooks = sinchClient.sms().v1().webhooks(); + + // ensure valid authentication to handle request + // See + // https://developers.sinch.com/docs/sms/api-reference/sms/tag/Webhooks/#tag/Webhooks/section/Callbacks + // Contact your account manager to configure your callback sending headers validation + // set "ensureValidAuthentication" value to true to validate requests from Sinch servers + boolean ensureValidAuthentication = false; + if (ensureValidAuthentication) { + var validAuth = + webhooks.validateAuthenticationHeader( + webhooksSecret, + // request headers + headers, + // request payload body + body); + + // token validation failed + if (!validAuth) { + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED); + } + } + + // decode the request payload + SmsEvent event = webhooks.parseEvent(body); + + // let business layer process the request + switch (event) { + case TextMessage e -> webhooksBusinessLogic.processInboundEvent(e); + default -> throw new IllegalStateException("Unexpected value: " + event); + } + + return ResponseEntity.ok().build(); + } +} diff --git a/examples/getting-started/sms/respond-to-incoming-message/src/main/java/com/mycompany/app/sms/ServerBusinessLogic.java b/examples/getting-started/sms/respond-to-incoming-message/src/main/java/com/mycompany/app/sms/ServerBusinessLogic.java new file mode 100644 index 000000000..00820c125 --- /dev/null +++ b/examples/getting-started/sms/respond-to-incoming-message/src/main/java/com/mycompany/app/sms/ServerBusinessLogic.java @@ -0,0 +1,40 @@ +package com.mycompany.app.sms; + +import com.sinch.sdk.SinchClient; +import com.sinch.sdk.domains.sms.api.v1.BatchesService; +import com.sinch.sdk.domains.sms.models.v1.batches.request.TextRequest; +import com.sinch.sdk.domains.sms.models.v1.batches.response.BatchResponse; +import com.sinch.sdk.domains.sms.models.v1.inbounds.TextMessage; +import java.util.Collections; +import java.util.logging.Logger; +import org.springframework.stereotype.Component; + +@Component("SMSServerBusinessLogic") +public class ServerBusinessLogic { + + private final BatchesService batches; + + public ServerBusinessLogic(SinchClient sinchClient) { + this.batches = sinchClient.sms().v1().batches(); + } + + private static final Logger LOGGER = Logger.getLogger(ServerBusinessLogic.class.getName()); + + public void processInboundEvent(TextMessage event) { + + LOGGER.info("Handle event: " + event); + + TextRequest smsRequest = + TextRequest.builder() + .setTo(Collections.singletonList(event.getFrom())) + .setBody("You sent: " + event.getBody()) + .setFrom(event.getTo()) + .build(); + + LOGGER.info("Replying with: " + smsRequest); + + BatchResponse response = batches.send(smsRequest); + + LOGGER.info("Response: " + response); + } +} diff --git a/examples/getting-started/sms/respond-to-incoming-message/src/main/resources/application.yaml b/examples/getting-started/sms/respond-to-incoming-message/src/main/resources/application.yaml new file mode 100644 index 000000000..e23d1fa40 --- /dev/null +++ b/examples/getting-started/sms/respond-to-incoming-message/src/main/resources/application.yaml @@ -0,0 +1,26 @@ +# springboot related config file + +logging: + level: + com: INFO + +server: + port: 8090 + +credentials: + # Required credentials for using the SMS API + # US/EU are the only supported regions with unified credentials + project-id: + key-id: + key-secret: + +sms: + # Sets the region for SMS + # valid values are "us" and "eu" + # See https://github.com/sinch/sinch-sdk-java/blob/main/client/src/main/com/sinch/sdk/models/SMSRegion.java for full list of supported values but with servicePlanID + #region: + webhooks: + # Used when "ensureValidAuthentication" within [Controller.java](../java/com/mycompany/app/sms/Controller.java) is set to true + secret: + + \ No newline at end of file diff --git a/examples/getting-started/sms/send-sms-message/README.md b/examples/getting-started/sms/send-sms-message/README.md new file mode 100644 index 000000000..98832eafe --- /dev/null +++ b/examples/getting-started/sms/send-sms-message/README.md @@ -0,0 +1,5 @@ +# Sinch Getting Started: Send an SMS Message (Java) + +Code is related to [Send an SMS Message with the Sinch Java SDK](https://developers.sinch.com/docs/sms/getting-started/java/send-sms-sdk). + +See [Client template README](../../../client/README.md) for details about configuration and usage. diff --git a/examples/getting-started/sms/send-sms-message/pom.xml b/examples/getting-started/sms/send-sms-message/pom.xml new file mode 100644 index 000000000..8ef76f558 --- /dev/null +++ b/examples/getting-started/sms/send-sms-message/pom.xml @@ -0,0 +1,94 @@ + + + 4.0.0 + + my.company.com + sinch-java-sdk-client-application + 1.0-SNAPSHOT + jar + Sinch Java SDK Client Application + + + + use-version + + ${env.SDK_VERSION} + + + + + + [2.0.0,) + 8 + 8 + 3.13.0 + UTF-8 + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.6.0 + + + add-sources + generate-sources + + add-source + + + + src/main/java + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + Application + + + + + jar-with-dependencies + + + + + package + + single + + + + + + + + + + + com.sinch.sdk + sinch-sdk-java + ${sinch.sdk.java.version} + + + + org.slf4j + slf4j-jdk14 + 2.0.9 + + + + + diff --git a/examples/getting-started/sms/send-sms-message/src/main/java/Application.java b/examples/getting-started/sms/send-sms-message/src/main/java/Application.java new file mode 100644 index 000000000..92958655b --- /dev/null +++ b/examples/getting-started/sms/send-sms-message/src/main/java/Application.java @@ -0,0 +1,42 @@ +import com.sinch.sdk.SinchClient; +import java.io.IOException; +import java.io.InputStream; +import java.util.logging.LogManager; +import java.util.logging.Logger; +import sms.SmsQuickStart; + +public abstract class Application { + + private static final String LOGGING_PROPERTIES_FILE = "logging.properties"; + private static final Logger LOGGER = initializeLogger(); + + public static void main(String[] args) { + try { + + SinchClient client = SinchClientHelper.initSinchClient(); + LOGGER.info("Application initiated. SinchClient ready."); + + SmsQuickStart sms = new SmsQuickStart(client.sms().v1()); + + } catch (Exception e) { + LOGGER.severe(String.format("Application failure: %s", e.getMessage())); + } + } + + static Logger initializeLogger() { + try (InputStream logConfigInputStream = + Application.class.getClassLoader().getResourceAsStream(LOGGING_PROPERTIES_FILE)) { + + if (logConfigInputStream != null) { + LogManager.getLogManager().readConfiguration(logConfigInputStream); + } else { + throw new RuntimeException( + String.format("The file '%s' couldn't be loaded.", LOGGING_PROPERTIES_FILE)); + } + + } catch (IOException e) { + throw new RuntimeException(e.getMessage()); + } + return Logger.getLogger(Application.class.getName()); + } +} diff --git a/examples/getting-started/sms/send-sms-message/src/main/java/SinchClientHelper.java b/examples/getting-started/sms/send-sms-message/src/main/java/SinchClientHelper.java new file mode 100644 index 000000000..3e45ad7eb --- /dev/null +++ b/examples/getting-started/sms/send-sms-message/src/main/java/SinchClientHelper.java @@ -0,0 +1,95 @@ +import com.sinch.sdk.SinchClient; +import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.SMSRegion; +import java.io.IOException; +import java.io.InputStream; +import java.util.Optional; +import java.util.Properties; +import java.util.logging.Logger; + +public class SinchClientHelper { + + private static final Logger LOGGER = Logger.getLogger(SinchClientHelper.class.getName()); + + private static final String SINCH_PROJECT_ID = "SINCH_PROJECT_ID"; + private static final String SINCH_KEY_ID = "SINCH_KEY_ID"; + private static final String SINCH_KEY_SECRET = "SINCH_KEY_SECRET"; + + private static final String SMS_SERVICE_PLAN_ID = "SMS_SERVICE_PLAN_ID"; + private static final String SMS_SERVICE_PLAN_TOKEN = "SMS_SERVICE_PLAN_TOKEN"; + private static final String SMS_REGION = "SMS_REGION"; + + private static final String CONFIG_FILE = "config.properties"; + + public static SinchClient initSinchClient() { + + LOGGER.info("Initializing client"); + + Configuration configuration = getConfiguration(); + + return new SinchClient(configuration); + } + + private static Configuration getConfiguration() { + + Properties properties = loadProperties(); + + Configuration.Builder builder = Configuration.builder(); + + manageUnifiedCredentials(properties, builder); + manageSmsConfiguration(properties, builder); + + return builder.build(); + } + + private static Properties loadProperties() { + + Properties properties = new Properties(); + + try (InputStream input = + SinchClientHelper.class.getClassLoader().getResourceAsStream(CONFIG_FILE)) { + if (input != null) { + properties.load(input); + } else { + LOGGER.severe(String.format("'%s' file could not be loaded", CONFIG_FILE)); + } + } catch (IOException e) { + LOGGER.severe(String.format("Error loading properties from '%s'", CONFIG_FILE)); + } + + return properties; + } + + static void manageUnifiedCredentials(Properties properties, Configuration.Builder builder) { + + Optional projectId = getConfigValue(properties, SINCH_PROJECT_ID); + Optional keyId = getConfigValue(properties, SINCH_KEY_ID); + Optional keySecret = getConfigValue(properties, SINCH_KEY_SECRET); + + projectId.ifPresent(builder::setProjectId); + keyId.ifPresent(builder::setKeyId); + keySecret.ifPresent(builder::setKeySecret); + } + + private static void manageSmsConfiguration(Properties properties, Configuration.Builder builder) { + + Optional servicePlanId = getConfigValue(properties, SMS_SERVICE_PLAN_ID); + Optional servicePlanToken = getConfigValue(properties, SMS_SERVICE_PLAN_TOKEN); + Optional region = getConfigValue(properties, SMS_REGION); + + servicePlanId.ifPresent(builder::setSmsServicePlanId); + servicePlanToken.ifPresent(builder::setSmsApiToken); + region.ifPresent(value -> builder.setSmsRegion(SMSRegion.from(value))); + } + + private static Optional getConfigValue(Properties properties, String key) { + String value = null != System.getenv(key) ? System.getenv(key) : properties.getProperty(key); + + // empty value means setting not set + if (null != value && value.trim().isEmpty()) { + return Optional.empty(); + } + + return Optional.ofNullable(value); + } +} diff --git a/examples/getting-started/sms/send-sms-message/src/main/java/sms/SmsQuickStart.java b/examples/getting-started/sms/send-sms-message/src/main/java/sms/SmsQuickStart.java new file mode 100644 index 000000000..316c98c36 --- /dev/null +++ b/examples/getting-started/sms/send-sms-message/src/main/java/sms/SmsQuickStart.java @@ -0,0 +1,15 @@ +package sms; + +import com.sinch.sdk.domains.sms.api.v1.SMSService; + +public class SmsQuickStart { + + private final SMSService smsService; + + public SmsQuickStart(SMSService smsService) { + this.smsService = smsService; + + // Insert your application logic or business process here + Snippet.execute(this.smsService); + } +} diff --git a/examples/getting-started/sms/send-sms-message/src/main/java/sms/Snippet.java b/examples/getting-started/sms/send-sms-message/src/main/java/sms/Snippet.java new file mode 100644 index 000000000..3142e9c60 --- /dev/null +++ b/examples/getting-started/sms/send-sms-message/src/main/java/sms/Snippet.java @@ -0,0 +1,34 @@ +package sms; + +import com.sinch.sdk.domains.sms.api.v1.BatchesService; +import com.sinch.sdk.domains.sms.api.v1.SMSService; +import com.sinch.sdk.domains.sms.models.v1.batches.request.TextRequest; +import com.sinch.sdk.domains.sms.models.v1.batches.response.BatchResponse; +import java.util.Collections; +import java.util.logging.Logger; + +public class Snippet { + + private static final Logger LOGGER = Logger.getLogger(Snippet.class.getName()); + + static void execute(SMSService smsService) { + + BatchesService batchesService = smsService.batches(); + + String sender = "SENDER_NUMBER"; + String recipient = "RECIPIENT_PHONE_NUMBER"; + String body = "This is a test SMS message using the Sinch Java SDK."; + + LOGGER.info(String.format("Submitting batch to send SMS to '%s'", recipient)); + + BatchResponse value = + batchesService.send( + TextRequest.builder() + .setTo(Collections.singletonList(recipient)) + .setBody(body) + .setFrom(sender) + .build()); + + LOGGER.info("Response: " + value); + } +} diff --git a/examples/getting-started/sms/send-sms-message/src/main/resources/config.properties b/examples/getting-started/sms/send-sms-message/src/main/resources/config.properties new file mode 100644 index 000000000..735ee8472 --- /dev/null +++ b/examples/getting-started/sms/send-sms-message/src/main/resources/config.properties @@ -0,0 +1,12 @@ +# Required credentials for using the SMS API +SINCH_PROJECT_ID= +SINCH_KEY_ID= +SINCH_KEY_SECRET= + +# Service related configuration +#SMS_REGION = us + +# SMS Service Plan ID related credentials +# if set, these credentials will be used and enable to use regions different of US/EU +#SMS_SERVICE_PLAN_ID = +#SMS_SERVICE_PLAN_TOKEN = diff --git a/examples/getting-started/sms/send-sms-message/src/main/resources/logging.properties b/examples/getting-started/sms/send-sms-message/src/main/resources/logging.properties new file mode 100644 index 000000000..5ed611e50 --- /dev/null +++ b/examples/getting-started/sms/send-sms-message/src/main/resources/logging.properties @@ -0,0 +1,8 @@ + +handlers = java.util.logging.ConsoleHandler +java.util.logging.ConsoleHandler.level = INFO +com.sinch.level = INFO + +java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter +java.util.logging.SimpleFormatter.format=[%1$tF %1$tT] [%4$-7s %2$s] %5$s %n + diff --git a/examples/getting-started/verification/user-verification-using-sms-pin/README.md b/examples/getting-started/verification/user-verification-using-sms-pin/README.md new file mode 100644 index 000000000..0ea2a7cdb --- /dev/null +++ b/examples/getting-started/verification/user-verification-using-sms-pin/README.md @@ -0,0 +1,5 @@ +# Sinch Getting Started: User Verification Using SMS PIN (Java) + +Code is related to [Verify a user using SMS PIN with the Java SDK](https://developers.sinch.com/docs/verification/getting-started/java-sdk/sms-verification/). + +See [Client template README](../../../client/README.md) for details about configuration and usage. diff --git a/examples/getting-started/verification/user-verification-using-sms-pin/pom.xml b/examples/getting-started/verification/user-verification-using-sms-pin/pom.xml new file mode 100644 index 000000000..a119e1e34 --- /dev/null +++ b/examples/getting-started/verification/user-verification-using-sms-pin/pom.xml @@ -0,0 +1,96 @@ + + + 4.0.0 + + my.company.com + sinch-java-sdk-client-application + 1.0-SNAPSHOT + jar + Sinch Java SDK Client Application + + + + use-version + + ${env.SDK_VERSION} + + + + + + [2.0.0,) + 8 + 8 + 3.13.0 + UTF-8 + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.6.0 + + + add-sources + generate-sources + + add-source + + + + src/main/java + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + Application + + + + + jar-with-dependencies + + + + + package + + single + + + + + + + + + + + com.sinch.sdk + sinch-sdk-java + ${sinch.sdk.java.version} + + + + + org.slf4j + slf4j-nop + 2.0.9 + + + + + diff --git a/examples/getting-started/verification/user-verification-using-sms-pin/src/main/java/Application.java b/examples/getting-started/verification/user-verification-using-sms-pin/src/main/java/Application.java new file mode 100644 index 000000000..3f1a58d3e --- /dev/null +++ b/examples/getting-started/verification/user-verification-using-sms-pin/src/main/java/Application.java @@ -0,0 +1,42 @@ +import com.sinch.sdk.SinchClient; +import java.io.IOException; +import java.io.InputStream; +import java.util.logging.LogManager; +import java.util.logging.Logger; +import verification.VerificationsSample; + +public abstract class Application { + + private static final String LOGGING_PROPERTIES_FILE = "logging.properties"; + private static final Logger LOGGER = initializeLogger(); + + public static void main(String[] args) { + try { + + SinchClient client = SinchClientHelper.initSinchClient(); + LOGGER.info("Application initiated. SinchClient ready."); + + new VerificationsSample(client.verification().v1()).start(); + + } catch (Exception e) { + LOGGER.severe(String.format("Application failure: %s", e.getMessage())); + } + } + + static Logger initializeLogger() { + try (InputStream logConfigInputStream = + Application.class.getClassLoader().getResourceAsStream(LOGGING_PROPERTIES_FILE)) { + + if (logConfigInputStream != null) { + LogManager.getLogManager().readConfiguration(logConfigInputStream); + } else { + throw new RuntimeException( + String.format("The file '%s' couldn't be loaded.", LOGGING_PROPERTIES_FILE)); + } + + } catch (IOException e) { + throw new RuntimeException(e.getMessage()); + } + return Logger.getLogger(Application.class.getName()); + } +} diff --git a/examples/getting-started/verification/user-verification-using-sms-pin/src/main/java/SinchClientHelper.java b/examples/getting-started/verification/user-verification-using-sms-pin/src/main/java/SinchClientHelper.java new file mode 100644 index 000000000..4b78d21ad --- /dev/null +++ b/examples/getting-started/verification/user-verification-using-sms-pin/src/main/java/SinchClientHelper.java @@ -0,0 +1,76 @@ +import com.sinch.sdk.SinchClient; +import com.sinch.sdk.models.Configuration; +import java.io.IOException; +import java.io.InputStream; +import java.util.Optional; +import java.util.Properties; +import java.util.logging.Logger; + +public class SinchClientHelper { + + private static final Logger LOGGER = Logger.getLogger(SinchClientHelper.class.getName()); + + private static final String APPLICATION_API_KEY = "APPLICATION_API_KEY"; + private static final String APPLICATION_API_SECRET = "APPLICATION_API_SECRET"; + + private static final String CONFIG_FILE = "config.properties"; + + public static SinchClient initSinchClient() { + + LOGGER.info("Initializing client"); + + Configuration configuration = getConfiguration(); + + return new SinchClient(configuration); + } + + private static Configuration getConfiguration() { + + Properties properties = loadProperties(); + + Configuration.Builder builder = Configuration.builder(); + + manageApplicationCredentials(properties, builder); + + return builder.build(); + } + + private static Properties loadProperties() { + + Properties properties = new Properties(); + + try (InputStream input = + SinchClientHelper.class.getClassLoader().getResourceAsStream(CONFIG_FILE)) { + if (input != null) { + properties.load(input); + } else { + LOGGER.severe(String.format("'%s' file could not be loaded", CONFIG_FILE)); + } + } catch (IOException e) { + LOGGER.severe(String.format("Error loading properties from '%s'", CONFIG_FILE)); + } + + return properties; + } + + private static void manageApplicationCredentials( + Properties properties, Configuration.Builder builder) { + + Optional verificationApiKey = getConfigValue(properties, APPLICATION_API_KEY); + Optional verificationApiSecret = getConfigValue(properties, APPLICATION_API_SECRET); + + verificationApiKey.ifPresent(builder::setApplicationKey); + verificationApiSecret.ifPresent(builder::setApplicationSecret); + } + + private static Optional getConfigValue(Properties properties, String key) { + String value = null != System.getenv(key) ? System.getenv(key) : properties.getProperty(key); + + // empty value means setting not set + if (null != value && value.trim().isEmpty()) { + return Optional.empty(); + } + + return Optional.ofNullable(value); + } +} diff --git a/examples/getting-started/verification/user-verification-using-sms-pin/src/main/java/verification/VerificationsSample.java b/examples/getting-started/verification/user-verification-using-sms-pin/src/main/java/verification/VerificationsSample.java new file mode 100644 index 000000000..53cff4e73 --- /dev/null +++ b/examples/getting-started/verification/user-verification-using-sms-pin/src/main/java/verification/VerificationsSample.java @@ -0,0 +1,143 @@ +package verification; + +import com.sinch.sdk.core.exceptions.ApiException; +import com.sinch.sdk.core.utils.StringUtil; +import com.sinch.sdk.domains.verification.api.v1.*; +import com.sinch.sdk.domains.verification.models.v1.NumberIdentity; +import com.sinch.sdk.domains.verification.models.v1.report.request.VerificationReportRequestSms; +import com.sinch.sdk.domains.verification.models.v1.report.response.VerificationReportResponseSms; +import com.sinch.sdk.domains.verification.models.v1.start.request.VerificationStartRequestSms; +import com.sinch.sdk.domains.verification.models.v1.start.response.VerificationStartResponseSms; +import com.sinch.sdk.models.E164PhoneNumber; +import java.util.Scanner; + +public class VerificationsSample { + + private final VerificationService verificationService; + + public VerificationsSample(VerificationService verificationService) { + this.verificationService = verificationService; + } + + public void start() { + + E164PhoneNumber e164Number = promptPhoneNumber(); + + try { + // Starting verification onto phone number + String id = startSmsVerification(verificationService.verificationStart(), e164Number); + + // Ask user for received code + Integer code = promptSmsCode(); + + // Submit the verification report + reportSmsVerification(verificationService.verificationReport(), code, id); + } catch (ApiException e) { + echo("Error (%d): %s", e.getCode(), e.getMessage()); + } + } + + /** + * Will start an SMS verification onto specified phone number + * + * @param service Verification Start service + * @param phoneNumber Destination phone number + * @return Verification ID + */ + private String startSmsVerification( + VerificationStartService service, E164PhoneNumber phoneNumber) { + + echo("Sending verification request onto '%s'", phoneNumber.stringValue()); + + VerificationStartRequestSms parameters = + VerificationStartRequestSms.builder() + .setIdentity(NumberIdentity.valueOf(phoneNumber)) + .build(); + + VerificationStartResponseSms response = service.startSms(parameters); + echo("Verification started with ID '%s'", response.getId()); + return response.getId(); + } + + /** + * Will use Sinch product to retrieve verification report by ID + * + * @param service Verification service + * @param code Code received by SMS + * @param id Verification ID related to the verification + */ + private void reportSmsVerification(VerificationReportService service, Integer code, String id) { + + VerificationReportRequestSms parameters = + VerificationReportRequestSms.builder().setCode(String.valueOf(code)).build(); + + echo("Requesting report for '%s'", id); + VerificationReportResponseSms response = service.reportSmsById(id, parameters); + echo("Report response: %s", response); + } + + /** + * Prompt user for a valid phone number + * + * @return Phone number value + */ + private E164PhoneNumber promptPhoneNumber() { + String input; + boolean valid; + do { + input = prompt("\nEnter a phone number to start verification"); + valid = E164PhoneNumber.validate(input); + if (!valid) { + echo("Invalid number '%s'", input); + } + } while (!valid); + + return E164PhoneNumber.valueOf(input); + } + + /** + * Prompt user for a SMS code + * + * @return Value entered by user + */ + private Integer promptSmsCode() { + Integer code = null; + do { + String input = prompt("Enter the verification code to report the verification"); + try { + code = Integer.valueOf(input); + } catch (NumberFormatException nfe) { + echo("Invalid value '%s' (code should be numeric)", input); + } + + } while (null == code); + return code; + } + + /** + * Endless loop for user input until a valid string is entered or 'Q' to quit + * + * @param prompt Prompt to be used task user a value + * @return The entered text from user + */ + private String prompt(String prompt) { + + String input = null; + Scanner scanner = new Scanner(System.in); + + while (StringUtil.isEmpty(input)) { + System.out.println(prompt + " ([Q] to quit): "); + input = scanner.nextLine(); + } + + if ("Q".equalsIgnoreCase(input)) { + System.out.println("Quit application"); + System.exit(0); + } + return input.trim(); + } + + private void echo(String text, Object... args) { + System.out.println(" " + String.format(text, args)); + } +} diff --git a/examples/getting-started/verification/user-verification-using-sms-pin/src/main/resources/config.properties b/examples/getting-started/verification/user-verification-using-sms-pin/src/main/resources/config.properties new file mode 100644 index 000000000..ff6010660 --- /dev/null +++ b/examples/getting-started/verification/user-verification-using-sms-pin/src/main/resources/config.properties @@ -0,0 +1,3 @@ +# Required credentials for using the Verification API +APPLICATION_API_KEY= +APPLICATION_API_SECRET= diff --git a/examples/getting-started/verification/user-verification-using-sms-pin/src/main/resources/logging.properties b/examples/getting-started/verification/user-verification-using-sms-pin/src/main/resources/logging.properties new file mode 100644 index 000000000..5ed611e50 --- /dev/null +++ b/examples/getting-started/verification/user-verification-using-sms-pin/src/main/resources/logging.properties @@ -0,0 +1,8 @@ + +handlers = java.util.logging.ConsoleHandler +java.util.logging.ConsoleHandler.level = INFO +com.sinch.level = INFO + +java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter +java.util.logging.SimpleFormatter.format=[%1$tF %1$tT] [%4$-7s %2$s] %5$s %n + diff --git a/examples/getting-started/voice/make-a-call/README.md b/examples/getting-started/voice/make-a-call/README.md new file mode 100644 index 000000000..f035ebc33 --- /dev/null +++ b/examples/getting-started/voice/make-a-call/README.md @@ -0,0 +1,5 @@ +# Sinch Getting Started: Make a Call (Java) + +Code is related to [Make a call with Java SDK](https://developers.sinch.com/docs/voice/getting-started/java-sdk/make-call/#make-a-call-with-java-sdk). + +See [Client template README](../../../client/README.md) for details about configuration and usage. diff --git a/examples/getting-started/voice/make-a-call/pom.xml b/examples/getting-started/voice/make-a-call/pom.xml new file mode 100644 index 000000000..8f257da18 --- /dev/null +++ b/examples/getting-started/voice/make-a-call/pom.xml @@ -0,0 +1,95 @@ + + + 4.0.0 + + my.company.com + sinch-java-sdk-client-application + 1.0-SNAPSHOT + jar + Sinch Java SDK Client Application + + + + + use-version + + ${env.SDK_VERSION} + + + + + + [2.0.0,) + 8 + 8 + 3.13.0 + UTF-8 + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.6.0 + + + add-sources + generate-sources + + add-source + + + + src/main/java + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + Application + + + + + jar-with-dependencies + + + + + package + + single + + + + + + + + + + + com.sinch.sdk + sinch-sdk-java + ${sinch.sdk.java.version} + + + + org.slf4j + slf4j-jdk14 + 2.0.9 + + + + + diff --git a/examples/getting-started/voice/make-a-call/src/main/java/Application.java b/examples/getting-started/voice/make-a-call/src/main/java/Application.java new file mode 100644 index 000000000..de21eb8ff --- /dev/null +++ b/examples/getting-started/voice/make-a-call/src/main/java/Application.java @@ -0,0 +1,42 @@ +import com.sinch.sdk.SinchClient; +import java.io.IOException; +import java.io.InputStream; +import java.util.logging.LogManager; +import java.util.logging.Logger; +import voice.VoiceQuickStart; + +public abstract class Application { + + private static final String LOGGING_PROPERTIES_FILE = "logging.properties"; + private static final Logger LOGGER = initializeLogger(); + + public static void main(String[] args) { + try { + + SinchClient client = SinchClientHelper.initSinchClient(); + LOGGER.info("Application initiated. SinchClient ready."); + + VoiceQuickStart voice = new VoiceQuickStart(client.voice().v1()); + + } catch (Exception e) { + LOGGER.severe(String.format("Application failure: %s", e.getMessage())); + } + } + + static Logger initializeLogger() { + try (InputStream logConfigInputStream = + Application.class.getClassLoader().getResourceAsStream(LOGGING_PROPERTIES_FILE)) { + + if (logConfigInputStream != null) { + LogManager.getLogManager().readConfiguration(logConfigInputStream); + } else { + throw new RuntimeException( + String.format("The file '%s' couldn't be loaded.", LOGGING_PROPERTIES_FILE)); + } + + } catch (IOException e) { + throw new RuntimeException(e.getMessage()); + } + return Logger.getLogger(Application.class.getName()); + } +} diff --git a/examples/getting-started/voice/make-a-call/src/main/java/SinchClientHelper.java b/examples/getting-started/voice/make-a-call/src/main/java/SinchClientHelper.java new file mode 100644 index 000000000..4b78d21ad --- /dev/null +++ b/examples/getting-started/voice/make-a-call/src/main/java/SinchClientHelper.java @@ -0,0 +1,76 @@ +import com.sinch.sdk.SinchClient; +import com.sinch.sdk.models.Configuration; +import java.io.IOException; +import java.io.InputStream; +import java.util.Optional; +import java.util.Properties; +import java.util.logging.Logger; + +public class SinchClientHelper { + + private static final Logger LOGGER = Logger.getLogger(SinchClientHelper.class.getName()); + + private static final String APPLICATION_API_KEY = "APPLICATION_API_KEY"; + private static final String APPLICATION_API_SECRET = "APPLICATION_API_SECRET"; + + private static final String CONFIG_FILE = "config.properties"; + + public static SinchClient initSinchClient() { + + LOGGER.info("Initializing client"); + + Configuration configuration = getConfiguration(); + + return new SinchClient(configuration); + } + + private static Configuration getConfiguration() { + + Properties properties = loadProperties(); + + Configuration.Builder builder = Configuration.builder(); + + manageApplicationCredentials(properties, builder); + + return builder.build(); + } + + private static Properties loadProperties() { + + Properties properties = new Properties(); + + try (InputStream input = + SinchClientHelper.class.getClassLoader().getResourceAsStream(CONFIG_FILE)) { + if (input != null) { + properties.load(input); + } else { + LOGGER.severe(String.format("'%s' file could not be loaded", CONFIG_FILE)); + } + } catch (IOException e) { + LOGGER.severe(String.format("Error loading properties from '%s'", CONFIG_FILE)); + } + + return properties; + } + + private static void manageApplicationCredentials( + Properties properties, Configuration.Builder builder) { + + Optional verificationApiKey = getConfigValue(properties, APPLICATION_API_KEY); + Optional verificationApiSecret = getConfigValue(properties, APPLICATION_API_SECRET); + + verificationApiKey.ifPresent(builder::setApplicationKey); + verificationApiSecret.ifPresent(builder::setApplicationSecret); + } + + private static Optional getConfigValue(Properties properties, String key) { + String value = null != System.getenv(key) ? System.getenv(key) : properties.getProperty(key); + + // empty value means setting not set + if (null != value && value.trim().isEmpty()) { + return Optional.empty(); + } + + return Optional.ofNullable(value); + } +} diff --git a/examples/getting-started/voice/make-a-call/src/main/java/voice/Snippet.java b/examples/getting-started/voice/make-a-call/src/main/java/voice/Snippet.java new file mode 100644 index 000000000..29d920d0d --- /dev/null +++ b/examples/getting-started/voice/make-a-call/src/main/java/voice/Snippet.java @@ -0,0 +1,34 @@ +package voice; + +import com.sinch.sdk.domains.voice.api.v1.CalloutsService; +import com.sinch.sdk.domains.voice.api.v1.VoiceService; +import com.sinch.sdk.domains.voice.models.v1.callouts.request.CalloutRequestTTS; +import com.sinch.sdk.domains.voice.models.v1.destination.DestinationPstn; +import java.util.logging.Logger; + +public class Snippet { + + private static final Logger LOGGER = Logger.getLogger(Snippet.class.getName()); + + public static String execute(VoiceService voiceService) { + + CalloutsService calloutsService = voiceService.callouts(); + + String phoneNumber = "PHONE_NUMBER"; + String message = "Hello, this is a call from Sinch. Congratulations! You made your first call."; + + LOGGER.info("Calling '" + phoneNumber + '"'); + + CalloutRequestTTS parameters = + CalloutRequestTTS.builder() + .setDestination(DestinationPstn.from(phoneNumber)) + .setText(message) + .build(); + + String callId = calloutsService.textToSpeech(parameters); + + LOGGER.info("Call started with id: '" + callId + '"'); + + return callId; + } +} diff --git a/examples/getting-started/voice/make-a-call/src/main/java/voice/VoiceQuickStart.java b/examples/getting-started/voice/make-a-call/src/main/java/voice/VoiceQuickStart.java new file mode 100644 index 000000000..a50b1ab11 --- /dev/null +++ b/examples/getting-started/voice/make-a-call/src/main/java/voice/VoiceQuickStart.java @@ -0,0 +1,15 @@ +package voice; + +import com.sinch.sdk.domains.voice.api.v1.VoiceService; + +public class VoiceQuickStart { + + private final VoiceService voiceService; + + public VoiceQuickStart(VoiceService voiceService) { + this.voiceService = voiceService; + + // Insert your application logic or business process here + Snippet.execute(this.voiceService); + } +} diff --git a/examples/getting-started/voice/make-a-call/src/main/resources/config.properties b/examples/getting-started/voice/make-a-call/src/main/resources/config.properties new file mode 100644 index 000000000..9e32513f5 --- /dev/null +++ b/examples/getting-started/voice/make-a-call/src/main/resources/config.properties @@ -0,0 +1,3 @@ +# Required credentials for using the Voice API +APPLICATION_API_KEY= +APPLICATION_API_SECRET= diff --git a/examples/getting-started/voice/make-a-call/src/main/resources/logging.properties b/examples/getting-started/voice/make-a-call/src/main/resources/logging.properties new file mode 100644 index 000000000..5ed611e50 --- /dev/null +++ b/examples/getting-started/voice/make-a-call/src/main/resources/logging.properties @@ -0,0 +1,8 @@ + +handlers = java.util.logging.ConsoleHandler +java.util.logging.ConsoleHandler.level = INFO +com.sinch.level = INFO + +java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter +java.util.logging.SimpleFormatter.format=[%1$tF %1$tT] [%4$-7s %2$s] %5$s %n + diff --git a/examples/getting-started/voice/respond-to-incoming-call/README.md b/examples/getting-started/voice/respond-to-incoming-call/README.md new file mode 100644 index 000000000..292d18230 --- /dev/null +++ b/examples/getting-started/voice/respond-to-incoming-call/README.md @@ -0,0 +1,5 @@ +# Sinch Getting Started: Respond to Incoming Call (Java) + +Code is related to [Handle an incoming call with Java SDK](https://developers.sinch.com/docs/voice/getting-started/java-sdk/incoming-call). + +See [Server template README](../../../webhooks/README.md) for details about configuration and usage. diff --git a/examples/getting-started/voice/respond-to-incoming-call/pom.xml b/examples/getting-started/voice/respond-to-incoming-call/pom.xml new file mode 100644 index 000000000..9876b452f --- /dev/null +++ b/examples/getting-started/voice/respond-to-incoming-call/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 3.2.5 + + + + my.company.com + sinch-java-sdk-server-application + 0.0.1-SNAPSHOT + Sinch Java SDK Server Application + + + + use-version + + ${env.SDK_VERSION} + + + + + + [2.0.0,) + 21 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-web + + + + com.sinch.sdk + sinch-sdk-java + ${sinch.sdk.java.version} + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/examples/getting-started/voice/respond-to-incoming-call/src/main/java/com/mycompany/app/Application.java b/examples/getting-started/voice/respond-to-incoming-call/src/main/java/com/mycompany/app/Application.java new file mode 100644 index 000000000..03b399f0f --- /dev/null +++ b/examples/getting-started/voice/respond-to-incoming-call/src/main/java/com/mycompany/app/Application.java @@ -0,0 +1,12 @@ +package com.mycompany.app; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/examples/getting-started/voice/respond-to-incoming-call/src/main/java/com/mycompany/app/Config.java b/examples/getting-started/voice/respond-to-incoming-call/src/main/java/com/mycompany/app/Config.java new file mode 100644 index 000000000..424ef345c --- /dev/null +++ b/examples/getting-started/voice/respond-to-incoming-call/src/main/java/com/mycompany/app/Config.java @@ -0,0 +1,36 @@ +package com.mycompany.app; + +import com.sinch.sdk.SinchClient; +import com.sinch.sdk.core.utils.StringUtil; +import com.sinch.sdk.models.Configuration; +import java.util.logging.Logger; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; + +@org.springframework.context.annotation.Configuration +public class Config { + + private static final Logger LOGGER = Logger.getLogger(Config.class.getName()); + + @Value("${credentials.application-api-key: }") + String applicationKey; + + @Value("${credentials.application-api-secret: }") + String applicationSecret; + + @Bean + public SinchClient sinchClient() { + + Configuration.Builder builder = Configuration.builder(); + + if (!StringUtil.isEmpty(applicationKey)) { + builder.setApplicationKey(applicationKey); + } + + if (!StringUtil.isEmpty(applicationSecret)) { + builder.setApplicationSecret(applicationSecret); + } + + return new SinchClient(builder.build()); + } +} diff --git a/examples/getting-started/voice/respond-to-incoming-call/src/main/java/com/mycompany/app/voice/Controller.java b/examples/getting-started/voice/respond-to-incoming-call/src/main/java/com/mycompany/app/voice/Controller.java new file mode 100644 index 000000000..c57b311c5 --- /dev/null +++ b/examples/getting-started/voice/respond-to-incoming-call/src/main/java/com/mycompany/app/voice/Controller.java @@ -0,0 +1,90 @@ +package com.mycompany.app.voice; + +import com.sinch.sdk.SinchClient; +import com.sinch.sdk.domains.voice.api.v1.WebHooksService; +import com.sinch.sdk.domains.voice.models.v1.webhooks.DisconnectedCallEvent; +import com.sinch.sdk.domains.voice.models.v1.webhooks.IncomingCallEvent; +import java.util.Map; +import java.util.logging.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +@RestController("Voice") +public class Controller { + + private final SinchClient sinchClient; + private final ServerBusinessLogic webhooksBusinessLogic; + private static final Logger LOGGER = Logger.getLogger(Controller.class.getName()); + + @Autowired + public Controller(SinchClient sinchClient, ServerBusinessLogic webhooksBusinessLogic) { + this.sinchClient = sinchClient; + this.webhooksBusinessLogic = webhooksBusinessLogic; + } + + @PostMapping( + value = "/VoiceEvent", + consumes = MediaType.APPLICATION_JSON_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity VoiceEvent( + @RequestHeader Map headers, @RequestBody String body) { + + WebHooksService webhooks = sinchClient.voice().v1().webhooks(); + + // ensure valid authentication to handle request + // see + // https://developers.sinch.com/docs/voice/api-reference/authentication/callback-signed-request + // for more information + // Contact your account manager to configure your callback sending headers validation + // set "ensureValidAuthentication" value to true to validate requests from Sinch servers + boolean ensureValidAuthentication = false; + if (ensureValidAuthentication) { + // ensure valid authentication to handle request + var validAuth = + webhooks.validateAuthenticationHeader( + // The HTTP verb this controller is managing + "POST", + // The URI this controller is managing + "/VoiceEvent", + // request headers + headers, + // request payload body + body); + + // token validation failed + if (!validAuth) { + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED); + } + } + + // decode the payload request + var event = webhooks.parseEvent(body); + + // let business layer process the request + var response = + switch (event) { + case IncomingCallEvent e -> webhooksBusinessLogic.incoming(e); + case DisconnectedCallEvent e -> { + webhooksBusinessLogic.disconnect(e); + yield null; + } + default -> throw new IllegalStateException("Unexpected value: " + event); + }; + + String serializedResponse = ""; + if (null != response) { + serializedResponse = webhooks.serializeResponse(response); + } + + LOGGER.finest("JSON response: " + serializedResponse); + + return ResponseEntity.ok().body(serializedResponse); + } +} diff --git a/examples/getting-started/voice/respond-to-incoming-call/src/main/java/com/mycompany/app/voice/ServerBusinessLogic.java b/examples/getting-started/voice/respond-to-incoming-call/src/main/java/com/mycompany/app/voice/ServerBusinessLogic.java new file mode 100644 index 000000000..c339699d3 --- /dev/null +++ b/examples/getting-started/voice/respond-to-incoming-call/src/main/java/com/mycompany/app/voice/ServerBusinessLogic.java @@ -0,0 +1,35 @@ +package com.mycompany.app.voice; + +import com.sinch.sdk.domains.voice.models.v1.svaml.SvamlControl; +import com.sinch.sdk.domains.voice.models.v1.svaml.action.SvamlActionHangup; +import com.sinch.sdk.domains.voice.models.v1.svaml.instruction.SvamlInstructionSay; +import com.sinch.sdk.domains.voice.models.v1.webhooks.DisconnectedCallEvent; +import com.sinch.sdk.domains.voice.models.v1.webhooks.IncomingCallEvent; +import java.util.Collections; +import java.util.logging.Logger; +import org.springframework.stereotype.Component; + +@Component("VoiceServerBusinessLogic") +public class ServerBusinessLogic { + + private static final Logger LOGGER = Logger.getLogger(ServerBusinessLogic.class.getName()); + + public SvamlControl incoming(IncomingCallEvent event) { + + LOGGER.info("Handle event: " + event); + + String instruction = + "Thank you for calling your Sinch number. You've just handled an incoming call."; + + return SvamlControl.builder() + .setAction(SvamlActionHangup.builder().build()) + .setInstructions( + Collections.singletonList(SvamlInstructionSay.builder().setText(instruction).build())) + .build(); + } + + public void disconnect(DisconnectedCallEvent event) { + + LOGGER.info("Handle event: " + event); + } +} diff --git a/examples/getting-started/voice/respond-to-incoming-call/src/main/resources/application.yaml b/examples/getting-started/voice/respond-to-incoming-call/src/main/resources/application.yaml new file mode 100644 index 000000000..f8d0e2115 --- /dev/null +++ b/examples/getting-started/voice/respond-to-incoming-call/src/main/resources/application.yaml @@ -0,0 +1,13 @@ +# springboot related config file + +logging: + level: + com: INFO + +server: + port: 8090 + +credentials: + # Required credentials for using the Voice API + application-api-key: + application-api-secret: diff --git a/examples/snippets/compile.sh b/examples/snippets/compile.sh index c121b1334..f573ca54d 100755 --- a/examples/snippets/compile.sh +++ b/examples/snippets/compile.sh @@ -2,4 +2,4 @@ mvn clean spotless:apply || exit 1 -./mvnw clean compile || exit 1 +./mvnw -Puse-version clean compile || exit 1 diff --git a/examples/snippets/pom.xml b/examples/snippets/pom.xml index 2f0a1d2e6..cb7355022 100644 --- a/examples/snippets/pom.xml +++ b/examples/snippets/pom.xml @@ -10,8 +10,17 @@ jar Sinch Java SDK Client Snippets + + + use-version + + ${env.SDK_VERSION} + + + + - [1.0.0,) + [2.0.0,) 8 8 3.13.0 diff --git a/examples/tutorials/compile.sh b/examples/tutorials/compile.sh new file mode 100755 index 000000000..5cf9851ae --- /dev/null +++ b/examples/tutorials/compile.sh @@ -0,0 +1,10 @@ +#!/bin/sh + +DIRECTORIES=" +voice/capture-leads-app +" + +for DIRECTORY in $DIRECTORIES +do + (cd "$DIRECTORY" && echo "$PWD" && mvn -Puse-version clean package) || exit 1 +done diff --git a/examples/tutorials/voice/capture-leads-app/README.md b/examples/tutorials/voice/capture-leads-app/README.md new file mode 100644 index 000000000..169fc3320 --- /dev/null +++ b/examples/tutorials/voice/capture-leads-app/README.md @@ -0,0 +1,80 @@ +# Sinch Java SDK Voice Tutorial: Qualify Leads + +This directory contains samples related to Java SDK tutorials: [qualify leads](https://developers.sinch.com/docs/voice/tutorials/qualify-leads/java) + +## DISCLAIMER + +This tutorial is based on mixing a command-line function with a server-side backend service. + +It is not a correct use of the CLI outside an educational purpose. + +## Requirements + +- JDK 21 or later +- [Maven](https://maven.apache.org/) +- [ngrok](https://ngrok.com/docs) +- [Sinch account](https://dashboard.sinch.com) + +## Usage + +### Configure application settings + +Application settings are using the SpringBoot configuration file: [`application.yaml`](src/main/resources/application.yaml) file and enable to configure: + +#### Required Sinch credentials + +Located in `credentials` section (*you can find all the credentials you need on your [Sinch dashboard](https://dashboard.sinch.com)*): + +- `application-api-key`: YOUR_application_key +- `application-api-secret`: YOUR_application_secret + +#### Other required values + +This tutorial uses other values that you should also assign: + +- `sinch-number`: This is the Sinch number assigned to your [Voice app](https://dashboard.sinch.com/voice/apps). +- `sip-address`: If you are performing this tutorial with a SIP infrastructure, this is where you would enter your SIP address. + +#### Server port + +Located in `server` section: + +- port: The port to be used to listen to incoming requests. Default: 8090 + +### Starting server locally + +Compile and run the application as server locally. + +```bash +mvn spring-boot:run +``` + +### Use ngrok to forward request to local server + +Forwarding request to same `8090` port used above: + +*Note: The `8090` value is coming from default config and can be changed (see [Server port](#Server-port) configuration section)* + +```bash +ngrok http 8090 +``` + +ngrok output will contains output like: + +```shell +ngrok (Ctrl+C to quit) + +... +Forwarding https://0e64-78-117-86-140.ngrok-free.app -> http://localhost:8090 + +``` + +The line + +```shell +Forwarding https://0e64-78-117-86-140.ngrok-free.app -> http://localhost:8090 +``` + +Contains `https://0e64-78-117-86-140.ngrok-free.app` value. + +This value must be used to configure the callback URL on your [Sinch dashboard](https://dashboard.sinch.com/voice/apps) \ No newline at end of file diff --git a/examples/tutorials/voice/capture-leads-app/pom.xml b/examples/tutorials/voice/capture-leads-app/pom.xml new file mode 100644 index 000000000..b0d2df995 --- /dev/null +++ b/examples/tutorials/voice/capture-leads-app/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.0.0 + + + + my.company.com + sinch-sdk-java-tuturial-auto-subscribe + 0.0.1-SNAPSHOT + Sinch Java SDK Capture Leads Sample Application + Demo Project for Capturing Leads + + + + use-version + + ${env.SDK_VERSION} + + + + + + [2.0.0,) + 21 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-web + + + + com.sinch.sdk + sinch-sdk-java + ${sinch.sdk.java.version} + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/examples/tutorials/voice/capture-leads-app/src/main/java/com/mycompany/app/Application.java b/examples/tutorials/voice/capture-leads-app/src/main/java/com/mycompany/app/Application.java new file mode 100644 index 000000000..03b399f0f --- /dev/null +++ b/examples/tutorials/voice/capture-leads-app/src/main/java/com/mycompany/app/Application.java @@ -0,0 +1,12 @@ +package com.mycompany.app; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/examples/tutorials/voice/capture-leads-app/src/main/java/com/mycompany/app/Config.java b/examples/tutorials/voice/capture-leads-app/src/main/java/com/mycompany/app/Config.java new file mode 100644 index 000000000..0401753cf --- /dev/null +++ b/examples/tutorials/voice/capture-leads-app/src/main/java/com/mycompany/app/Config.java @@ -0,0 +1,29 @@ +package com.mycompany.app; + +import com.sinch.sdk.SinchClient; +import com.sinch.sdk.domains.voice.VoiceService; +import com.sinch.sdk.models.Configuration; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; + +@org.springframework.context.annotation.Configuration +public class Config { + + @Value("${credentials.application-api-key}") + String applicationKey; + + @Value("${credentials.application-api-secret}") + String applicationSecret; + + @Bean + public VoiceService voiceService() { + + var configuration = + Configuration.builder() + .setApplicationKey(applicationKey) + .setApplicationSecret(applicationSecret) + .build(); + + return new SinchClient(configuration).voice(); + } +} diff --git a/examples/tutorials/voice/capture-leads-app/src/main/java/com/mycompany/app/voice/CLIHelper.java b/examples/tutorials/voice/capture-leads-app/src/main/java/com/mycompany/app/voice/CLIHelper.java new file mode 100644 index 000000000..21cf8124f --- /dev/null +++ b/examples/tutorials/voice/capture-leads-app/src/main/java/com/mycompany/app/voice/CLIHelper.java @@ -0,0 +1,96 @@ +package com.mycompany.app.voice; + +import com.sinch.sdk.core.utils.StringUtil; +import com.sinch.sdk.domains.voice.VoiceService; +import com.sinch.sdk.domains.voice.api.v1.CalloutsService; +import com.sinch.sdk.domains.voice.models.v1.callouts.request.CalloutRequestCustom; +import com.sinch.sdk.domains.voice.models.v1.svaml.SvamlControl; +import com.sinch.sdk.domains.voice.models.v1.svaml.action.AnsweringMachineDetectionQuery; +import com.sinch.sdk.domains.voice.models.v1.svaml.action.SvamlActionConnectPstn; +import com.sinch.sdk.models.E164PhoneNumber; +import java.util.Scanner; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Component; + +@Component +public class CLIHelper implements CommandLineRunner { + + @Value("${sinch-number}") + String sinchNumber; + + private final CalloutsService calloutsService; + + @Autowired + public CLIHelper(VoiceService voiceService) { + this.calloutsService = voiceService.v1().callouts(); + } + + @Override + public void run(String... args) { + + while (true) { + String phoneNumber = promptPhoneNumber(); + + proceedCallout(phoneNumber); + } + } + + void proceedCallout(String phoneNumber) { + var response = + calloutsService.custom( + CalloutRequestCustom.builder() + .setIce( + SvamlControl.builder() + .setAction( + SvamlActionConnectPstn.builder() + .setNumber(phoneNumber) + .setCli(sinchNumber) + .setAmd( + AnsweringMachineDetectionQuery.builder() + .setEnabled(true) + .build()) + .build()) + .build()) + .build()); + + echo("Callout response: '%s'", response); + } + + private String promptPhoneNumber() { + String input; + boolean valid; + do { + input = prompt("\nEnter the phone number you want to call"); + valid = E164PhoneNumber.validate(input); + if (!valid) { + echo("Invalid number '%s'", input); + } + } while (!valid); + + return input; + } + + private String prompt(String prompt) { + + String input = null; + Scanner scanner = new Scanner(System.in); + + while (StringUtil.isEmpty(input)) { + System.out.println(prompt + " ([Q] to quit): "); + input = scanner.nextLine(); + } + + if ("Q".equalsIgnoreCase(input)) { + System.out.println("Quit application"); + System.exit(0); + } + + return input.replaceAll(" ", ""); + } + + private void echo(String text, Object... args) { + System.out.println(" " + String.format(text, args)); + } +} diff --git a/examples/tutorials/voice/capture-leads-app/src/main/java/com/mycompany/app/voice/Controller.java b/examples/tutorials/voice/capture-leads-app/src/main/java/com/mycompany/app/voice/Controller.java new file mode 100644 index 000000000..618dc179c --- /dev/null +++ b/examples/tutorials/voice/capture-leads-app/src/main/java/com/mycompany/app/voice/Controller.java @@ -0,0 +1,93 @@ +package com.mycompany.app.voice; + +import com.sinch.sdk.domains.voice.VoiceService; +import com.sinch.sdk.domains.voice.api.v1.WebHooksService; +import com.sinch.sdk.domains.voice.models.v1.svaml.SvamlControl; +import com.sinch.sdk.domains.voice.models.v1.webhooks.AnsweredCallEvent; +import com.sinch.sdk.domains.voice.models.v1.webhooks.PromptInputEvent; +import java.util.Map; +import java.util.Optional; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +@RestController("Voice") +public class Controller { + + private final WebHooksService webhooks; + private final ServerBusinessLogic webhooksBusinessLogic; + + @Autowired + public Controller(VoiceService voiceService, ServerBusinessLogic webhooksBusinessLogic) { + this.webhooks = voiceService.v1().webhooks(); + this.webhooksBusinessLogic = webhooksBusinessLogic; + } + + @PostMapping( + value = "/VoiceEvent", + consumes = MediaType.APPLICATION_JSON_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity VoiceEvent( + @RequestHeader Map headers, @RequestBody String body) { + + validateRequest(headers, body); + + // decode the request payload + var event = webhooks.parseEvent(body); + + Optional response = Optional.empty(); + + // let business layer process the request + if (event instanceof AnsweredCallEvent e) { + response = Optional.of(webhooksBusinessLogic.answeredCallEvent(e)); + } + if (event instanceof PromptInputEvent e) { + response = Optional.of(webhooksBusinessLogic.promptInputEvent(e)); + } + + if (response.isEmpty()) { + return ResponseEntity.ok().body(null); + } + + ResponseEntity responseEntity = ResponseEntity.ok().body(null); + + String serializedResponse = webhooks.serializeResponse(response.get()); + + return ResponseEntity.ok().body(serializedResponse); + } + + void validateRequest(Map headers, String body) { + + // ensure valid authentication to handle request + // set this value to true to validate request from Sinch servers + // see + // https://developers.sinch.com/docs/voice/api-reference/authentication/callback-signed-request + // for more information + boolean ensureValidAuthentication = false; + if (ensureValidAuthentication) { + return; + } + + var validAuth = + webhooks.validateAuthenticationHeader( + // The HTTP verb this controller is managing + "POST", + // The URI this controller is managing + "/VoiceEvent", + // request headers + headers, + // request payload body + body); + + // token validation failed + if (!validAuth) { + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED); + } + } +} diff --git a/examples/tutorials/voice/capture-leads-app/src/main/java/com/mycompany/app/voice/ServerBusinessLogic.java b/examples/tutorials/voice/capture-leads-app/src/main/java/com/mycompany/app/voice/ServerBusinessLogic.java new file mode 100644 index 000000000..e8d4286f6 --- /dev/null +++ b/examples/tutorials/voice/capture-leads-app/src/main/java/com/mycompany/app/voice/ServerBusinessLogic.java @@ -0,0 +1,166 @@ +package com.mycompany.app.voice; + +import com.sinch.sdk.domains.voice.models.v1.destination.DestinationSip; +import com.sinch.sdk.domains.voice.models.v1.svaml.SvamlControl; +import com.sinch.sdk.domains.voice.models.v1.svaml.action.Menu; +import com.sinch.sdk.domains.voice.models.v1.svaml.action.MenuOption; +import com.sinch.sdk.domains.voice.models.v1.svaml.action.MenuOptionActionFactory; +import com.sinch.sdk.domains.voice.models.v1.svaml.action.SvamlActionConnectSip; +import com.sinch.sdk.domains.voice.models.v1.svaml.action.SvamlActionConnectSip.TransportEnum; +import com.sinch.sdk.domains.voice.models.v1.svaml.action.SvamlActionHangup; +import com.sinch.sdk.domains.voice.models.v1.svaml.action.SvamlActionRunMenu; +import com.sinch.sdk.domains.voice.models.v1.svaml.instruction.SvamlInstructionSay; +import com.sinch.sdk.domains.voice.models.v1.webhooks.AnsweredCallEvent; +import com.sinch.sdk.domains.voice.models.v1.webhooks.AnsweringMachineDetection.StatusEnum; +import com.sinch.sdk.domains.voice.models.v1.webhooks.PromptInputEvent; +import com.sinch.sdk.models.DualToneMultiFrequency; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component("VoiceServerBusinessLogic") +public class ServerBusinessLogic { + + private final String SIP_MENU = "sip"; + + private final String NON_SIP_MENU = "non-sip"; + + @Value("${sinch-number}") + String sinchNumber; + + @Value("${sip-address}") + String sipAddress; + + public SvamlControl answeredCallEvent(AnsweredCallEvent event) { + + var amdResult = event.getAmd(); + + if (StatusEnum.MACHINE.equals(amdResult.getStatus())) { + return machineResponse(); + } + if (StatusEnum.HUMAN.equals(amdResult.getStatus())) { + return humanResponse(); + } + throw new IllegalStateException("Unexpected value: " + event); + } + + public SvamlControl promptInputEvent(PromptInputEvent event) { + var menuResult = event.getMenuResult(); + + if (SIP_MENU.equals(menuResult.getValue())) { + return sipResponse(); + } + if (NON_SIP_MENU.equals(menuResult.getValue())) { + return nonSipResponse(); + } + return defaultResponse(); + } + + private SvamlControl sipResponse() { + + String instruction = + "Thanks for agreeing to speak to one of our sales reps! We'll now connect your call."; + + return SvamlControl.builder() + .setAction( + SvamlActionConnectSip.builder() + .setDestination(DestinationSip.from(sipAddress)) + .setCli(sinchNumber) + .setTransport(TransportEnum.TLS) + .build()) + .setInstructions( + Collections.singletonList(SvamlInstructionSay.builder().setText(instruction).build())) + .build(); + } + + private SvamlControl nonSipResponse() { + + String instruction = + "Thank you for choosing to speak to one of our sales reps! If this were in production, at" + + " this point you would be connected to a sales rep on your sip network. Since you do" + + " not, you have now completed this tutorial. We hope you had fun and learned" + + " something new. Be sure to keep visiting https://developers.sinch.com for more great" + + " tutorials."; + + return SvamlControl.builder() + .setAction(SvamlActionHangup.builder().build()) + .setInstructions( + Collections.singletonList(SvamlInstructionSay.builder().setText(instruction).build())) + .build(); + } + + private SvamlControl defaultResponse() { + + String instruction = "Thank you for trying our tutorial! This call will now end."; + + return SvamlControl.builder() + .setAction(SvamlActionHangup.builder().build()) + .setInstructions( + Collections.singletonList(SvamlInstructionSay.builder().setText(instruction).build())) + .build(); + } + + private SvamlControl humanResponse() { + + String SIP_MENU_OPTION = "1"; + String NON_SIP_MENU_OPTION = "2"; + + String mainPrompt = + String.format( + "#tts[Hi, you awesome person! Press '%s' if you have performed this tutorial using a" + + " sip infrastructure. Press '%s' if you have not used a sip infrastructure. Press" + + " any other digit to end this call.]", + SIP_MENU_OPTION, NON_SIP_MENU_OPTION); + + String repeatPrompt = + String.format( + "#tts[Again, simply press '%s' if you have used sip, press '%s' if you have not, or" + + " press any other digit to end this call.]", + SIP_MENU_OPTION, NON_SIP_MENU_OPTION); + + MenuOption option1 = + MenuOption.builder() + .setDtmf(DualToneMultiFrequency.valueOf(SIP_MENU_OPTION)) + .setAction(MenuOptionActionFactory.returnAction(SIP_MENU)) + .build(); + + MenuOption option2 = + MenuOption.builder() + .setDtmf(DualToneMultiFrequency.valueOf(NON_SIP_MENU_OPTION)) + .setAction(MenuOptionActionFactory.returnAction(NON_SIP_MENU)) + .build(); + + List options = Arrays.asList(option1, option2); + + return SvamlControl.builder() + .setAction( + SvamlActionRunMenu.builder() + .setBarge(false) + .setMenus( + Collections.singletonList( + Menu.builder() + .setId("main") + .setMainPrompt(mainPrompt) + .setRepeatPrompt(repeatPrompt) + .setRepeats(2) + .setOptions(options) + .build())) + .build()) + .build(); + } + + private SvamlControl machineResponse() { + + String instruction = + "Hi there! We tried to reach you to speak with you about our awesome products. We will try" + + " again later. Bye!"; + + return SvamlControl.builder() + .setAction(SvamlActionHangup.builder().build()) + .setInstructions( + Collections.singletonList(SvamlInstructionSay.builder().setText(instruction).build())) + .build(); + } +} diff --git a/examples/tutorials/voice/capture-leads-app/src/main/resources/application.yaml b/examples/tutorials/voice/capture-leads-app/src/main/resources/application.yaml new file mode 100644 index 000000000..54512e224 --- /dev/null +++ b/examples/tutorials/voice/capture-leads-app/src/main/resources/application.yaml @@ -0,0 +1,16 @@ +# springboot related config file + +logging: + level: + com: INFO + +server: + port: 8090 + +credentials: + application-api-key: + application-api-secret: + +# see README.md, "Required values" section for details about these settings +sinch-number: +sip-address: diff --git a/examples/webhooks/.mvn/wrapper/maven-wrapper.properties b/examples/webhooks/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 000000000..d58dfb70b --- /dev/null +++ b/examples/webhooks/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/examples/webhooks/README.md b/examples/webhooks/README.md new file mode 100644 index 000000000..a2a60953d --- /dev/null +++ b/examples/webhooks/README.md @@ -0,0 +1,79 @@ +# Backend application built using Sinch Java SDK to handle incoming webhooks + +This directory contains a server application based on the [Sinch SDK java](https://github.com/sinch/sinch-sdk-java) + +## Requirements + +- JDK 21 or later (Sinch SDK Java is requiring java 8 only but client application can use latest available version) +- [Maven](https://maven.apache.org/) +- [SpringBoot](https://spring.io/projects/spring-boot) +- [Sinch account](https://dashboard.sinch.com) +- [ngrok](https://ngrok.com/docs) + +## Configuration + +### Configure application settings + +com.mycompany.app.Application settings are using the `SpringBoot` configuration file: [`application.yaml`](src/main/resources/application.yaml) file and enable to configure: + +#### Sinch credentials +Located in `credentials` section (*you can find all the credentials you need on your [Sinch dashboard](https://dashboard.sinch.com)*): +- `project-id`: YOUR_project_id +- `key-id`: YOUR_access_key_id +- `key-secret`: YOUR_access_key_secret + +#### Server port +Default: 8090 + +Located in `server` section: +- port: The port to be used to listen to incoming requests. Default: 8090 + +## Usage + +### Start server +1. Edit configuration file + + See above for [Configuration](#configuration) paragraph + +2. Start server locally. + + Compile and run the application as server locally. + ```bash + ./mvnw clean spring-boot:run + ``` +### EndPoints +When server is online, declared controllers will respond to following endpoints + +| Service | Endpoint | +|------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------| +| [Conversation](https://developers.sinch.com/docs/conversation/callbacks) | /ConversationEvent | +| [Numbers](https://developers.sinch.com/docs/numbers/api-reference/numbers/tag/Numbers-Callbacks/#tag/Numbers-Callbacks/operation/ImportedNumberService_EventsCallback) | /NumbersEvent | +| [SMS](https://developers.sinch.com/docs/sms/api-reference/sms/tag/Webhooks/#tag/Webhooks/section/Callbacks) | /SmsEvent | +| [Verification](https://developers.sinch.com/docs/verification/api-reference/verification/tag/Verification-callbacks/) | /VerificationEvent | +| [Voice](https://developers.sinch.com/docs/voice/api-reference/voice/tag/Callbacks/) | /VoiceEvent | + +## Use ngrok to forward request to local server + +Forwarding request to same `8090` port used above: + +*Note: The `8090` value is coming from default config and can be changed (see [Server port](#Server port) configuration section)* + +```bash +ngrok http 8090 +``` + +ngrok output will contains output like: +``` +ngrok (Ctrl+C to quit) + +... +Forwarding https://0e64-78-117-86-140.ngrok-free.app -> http://localhost:8090 + +``` +The line +``` +Forwarding https://0e64-78-117-86-140.ngrok-free.app -> http://localhost:8090 +``` +Contains `https://0e64-78-117-86-140.ngrok-free.app` value. + +This value must be used to configure callback's URL from your [Sinch dashboard](https://dashboard.sinch.com/sms/api/services) \ No newline at end of file diff --git a/examples/webhooks/compile.sh b/examples/webhooks/compile.sh new file mode 100755 index 000000000..bfac33627 --- /dev/null +++ b/examples/webhooks/compile.sh @@ -0,0 +1,5 @@ +#!/bin/sh + +mvn clean spotless:apply || exit 1 + +./mvnw -Puse-version clean compile || exit 1 diff --git a/examples/webhooks/mvnw b/examples/webhooks/mvnw new file mode 100755 index 000000000..19529ddf8 --- /dev/null +++ b/examples/webhooks/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/examples/webhooks/mvnw.cmd b/examples/webhooks/mvnw.cmd new file mode 100644 index 000000000..b150b91ed --- /dev/null +++ b/examples/webhooks/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/examples/webhooks/pom.xml b/examples/webhooks/pom.xml new file mode 100644 index 000000000..1eba25ac5 --- /dev/null +++ b/examples/webhooks/pom.xml @@ -0,0 +1,99 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.0.0 + + + + my.company.com + sinch-java-sdk-webhooks-application + 0.0.1-SNAPSHOT + Sinch Java SDK Webhooks Application + + + + use-version + + ${env.SDK_VERSION} + + + + + + [2.0.0,) + 21 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-web + + + + com.sinch.sdk + sinch-sdk-java + ${sinch.sdk.java.version} + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + com.diffplug.spotless + spotless-maven-plugin + 2.40.0 + + + + + + **/*.java + + + + 1.22.0 + true + + + + + true + 2 + + + + + + + + + verify + + check + + + + + + + + + diff --git a/examples/webhooks/src/main/java/com/mycompany/app/Application.java b/examples/webhooks/src/main/java/com/mycompany/app/Application.java new file mode 100644 index 000000000..03b399f0f --- /dev/null +++ b/examples/webhooks/src/main/java/com/mycompany/app/Application.java @@ -0,0 +1,12 @@ +package com.mycompany.app; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/examples/webhooks/src/main/java/com/mycompany/app/Config.java b/examples/webhooks/src/main/java/com/mycompany/app/Config.java new file mode 100644 index 000000000..427dfb342 --- /dev/null +++ b/examples/webhooks/src/main/java/com/mycompany/app/Config.java @@ -0,0 +1,74 @@ +package com.mycompany.app; + +import com.sinch.sdk.SinchClient; +import com.sinch.sdk.core.utils.StringUtil; +import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.ConversationRegion; +import com.sinch.sdk.models.SMSRegion; +import java.util.logging.Logger; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; + +@org.springframework.context.annotation.Configuration +public class Config { + + private static final Logger LOGGER = Logger.getLogger(Config.class.getName()); + + @Value("${credentials.project-id: }") + String projectId; + + @Value("${credentials.key-id: }") + String keyId; + + @Value("${credentials.key-secret: }") + String keySecret; + + @Value("${credentials.application-api-key: }") + String applicationKey; + + @Value("${credentials.application-api-secret: }") + String applicationSecret; + + @Value("${conversation.region: }") + String conversationRegion; + + @Value("${sms.region: }") + String smsRegion; + + @Bean + public SinchClient sinchClient() { + + Configuration.Builder builder = Configuration.builder(); + + if (!StringUtil.isEmpty(projectId)) { + builder.setProjectId(projectId); + } + + if (!StringUtil.isEmpty(keyId)) { + builder.setKeyId(keyId); + } + if (!StringUtil.isEmpty(keySecret)) { + builder.setKeySecret(keySecret); + } + + if (!StringUtil.isEmpty(applicationKey)) { + builder.setApplicationKey(applicationKey); + } + + if (!StringUtil.isEmpty(applicationSecret)) { + builder.setApplicationSecret(applicationSecret); + } + + if (!StringUtil.isEmpty(conversationRegion)) { + builder.setConversationRegion(ConversationRegion.from(conversationRegion)); + LOGGER.info(String.format("Conversation region: '%s'", conversationRegion)); + } + + if (!StringUtil.isEmpty(smsRegion)) { + builder.setSmsRegion(SMSRegion.from(smsRegion)); + LOGGER.info(String.format("SMS region: '%s'", smsRegion)); + } + + return new SinchClient(builder.build()); + } +} diff --git a/examples/webhooks/src/main/java/com/mycompany/app/conversation/Controller.java b/examples/webhooks/src/main/java/com/mycompany/app/conversation/Controller.java new file mode 100644 index 000000000..befb0835a --- /dev/null +++ b/examples/webhooks/src/main/java/com/mycompany/app/conversation/Controller.java @@ -0,0 +1,111 @@ +package com.mycompany.app.conversation; + +import com.sinch.sdk.SinchClient; +import com.sinch.sdk.domains.conversation.api.v1.WebHooksService; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.ConversationWebhookEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.capability.CapabilityEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.channel.ChannelEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.contact.ContactCreateEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.contact.ContactDeleteEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.contact.ContactIdentitiesDuplicationEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.contact.ContactMergeEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.contact.ContactUpdateEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.conversation.ConversationDeleteEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.conversation.ConversationStartEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.conversation.ConversationStopEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.delivery.EventDeliveryReceiptEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.delivery.MessageDeliveryReceiptEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.inbound.InboundEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.message.MessageInboundEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.message.MessageSubmitEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.opting.OptInEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.opting.OptOutEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.record.RecordNotificationEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.smartconversations.MessageInboundSmartConversationRedactionEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.smartconversations.SmartConversationsEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.unsupported.UnsupportedCallbackEvent; +import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +@RestController("Conversation") +public class Controller { + + private final SinchClient sinchClient; + private final ServerBusinessLogic webhooksBusinessLogic; + + @Value("${conversation.webhooks.secret: }") + private String webhooksSecret; + + @Autowired + public Controller(SinchClient sinchClient, ServerBusinessLogic webhooksBusinessLogic) { + this.sinchClient = sinchClient; + this.webhooksBusinessLogic = webhooksBusinessLogic; + } + + @PostMapping( + value = "/ConversationEvent", + consumes = MediaType.APPLICATION_JSON_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity ConversationEvent( + @RequestHeader Map headers, @RequestBody String body) { + + WebHooksService webhooks = sinchClient.conversation().v1().webhooks(); + + // set this value to true to validate request from Sinch servers + // see https://developers.sinch.com/docs/numbers/api-reference/numbers/tag/Numbers-Callbacks for + // more information + boolean ensureValidAuthentication = false; + if (ensureValidAuthentication) { + // ensure valid authentication to handle request + var validAuth = webhooks.validateAuthenticationHeader(webhooksSecret, headers, body); + + // token validation failed + if (!validAuth) { + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED); + } + } + + // decode the request payload + ConversationWebhookEvent event = webhooks.parseEvent(body); + + // let business layer process the request + switch (event) { + case CapabilityEvent e -> webhooksBusinessLogic.handleCapabilityEvent(e); + case ChannelEvent e -> webhooksBusinessLogic.handleChannelEvent(e); + case ContactCreateEvent e -> webhooksBusinessLogic.handleContactCreateEvent(e); + case ContactDeleteEvent e -> webhooksBusinessLogic.handleContactDeleteEvent(e); + case ContactIdentitiesDuplicationEvent e -> + webhooksBusinessLogic.handleContactIdentitiesDuplicationEvent(e); + case ContactMergeEvent e -> webhooksBusinessLogic.handleContactMergeEvent(e); + case ContactUpdateEvent e -> webhooksBusinessLogic.handleContactUpdateEvent(e); + case ConversationDeleteEvent e -> webhooksBusinessLogic.handleConversationDeleteEvent(e); + case ConversationStartEvent e -> webhooksBusinessLogic.handleConversationStartEvent(e); + case ConversationStopEvent e -> webhooksBusinessLogic.handleConversationStopEvent(e); + case EventDeliveryReceiptEvent e -> webhooksBusinessLogic.handleEventDeliveryReceiptEvent(e); + case InboundEvent e -> webhooksBusinessLogic.handleInboundEvent(e); + case MessageDeliveryReceiptEvent e -> + webhooksBusinessLogic.handleMessageDeliveryReceiptEvent(e); + case MessageInboundEvent e -> webhooksBusinessLogic.handleMessageInboundEvent(e); + case MessageInboundSmartConversationRedactionEvent e -> + webhooksBusinessLogic.handleMessageInboundSmartConversationRedactionEvent(e); + case MessageSubmitEvent e -> webhooksBusinessLogic.handleMessageSubmitEvent(e); + case OptInEvent e -> webhooksBusinessLogic.handleOptInEvent(e); + case OptOutEvent e -> webhooksBusinessLogic.handleOptOutEvent(e); + case RecordNotificationEvent e -> webhooksBusinessLogic.handleRecordNotificationEvent(e); + case SmartConversationsEvent e -> webhooksBusinessLogic.handleSmartConversationsEvent(e); + case UnsupportedCallbackEvent e -> webhooksBusinessLogic.handleUnsupportedCallbackEvent(e); + default -> throw new IllegalStateException("Unexpected value: " + event); + } + + return ResponseEntity.ok().build(); + } +} diff --git a/examples/webhooks/src/main/java/com/mycompany/app/conversation/ServerBusinessLogic.java b/examples/webhooks/src/main/java/com/mycompany/app/conversation/ServerBusinessLogic.java new file mode 100644 index 000000000..f4a8458b3 --- /dev/null +++ b/examples/webhooks/src/main/java/com/mycompany/app/conversation/ServerBusinessLogic.java @@ -0,0 +1,137 @@ +package com.mycompany.app.conversation; + +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.capability.CapabilityEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.channel.ChannelEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.contact.ContactCreateEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.contact.ContactDeleteEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.contact.ContactIdentitiesDuplicationEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.contact.ContactMergeEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.contact.ContactUpdateEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.conversation.ConversationDeleteEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.conversation.ConversationStartEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.conversation.ConversationStopEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.delivery.EventDeliveryReceiptEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.delivery.MessageDeliveryReceiptEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.inbound.InboundEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.message.MessageInboundEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.message.MessageSubmitEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.opting.OptInEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.opting.OptOutEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.record.RecordNotificationEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.smartconversations.MessageInboundSmartConversationRedactionEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.smartconversations.SmartConversationsEvent; +import com.sinch.sdk.domains.conversation.models.v1.webhooks.events.unsupported.UnsupportedCallbackEvent; +import java.util.logging.Logger; +import org.springframework.stereotype.Component; + +@Component("ConversationServerBusinessLogic") +public class ServerBusinessLogic { + + private static final Logger LOGGER = Logger.getLogger(ServerBusinessLogic.class.getName()); + + public void handleCapabilityEvent(CapabilityEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void handleChannelEvent(ChannelEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void handleContactCreateEvent(ContactCreateEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void handleContactDeleteEvent(ContactDeleteEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void handleContactIdentitiesDuplicationEvent(ContactIdentitiesDuplicationEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void handleContactMergeEvent(ContactMergeEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void handleContactUpdateEvent(ContactUpdateEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void handleConversationDeleteEvent(ConversationDeleteEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void handleConversationStartEvent(ConversationStartEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void handleConversationStopEvent(ConversationStopEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void handleEventDeliveryReceiptEvent(EventDeliveryReceiptEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void handleInboundEvent(InboundEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void handleMessageDeliveryReceiptEvent(MessageDeliveryReceiptEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void handleMessageInboundEvent(MessageInboundEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void handleMessageInboundSmartConversationRedactionEvent( + MessageInboundSmartConversationRedactionEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void handleMessageSubmitEvent(MessageSubmitEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void handleOptInEvent(OptInEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void handleOptOutEvent(OptOutEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void handleRecordNotificationEvent(RecordNotificationEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void handleSmartConversationsEvent(SmartConversationsEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void handleUnsupportedCallbackEvent(UnsupportedCallbackEvent event) { + + LOGGER.info("Handle event: " + event); + } +} diff --git a/examples/webhooks/src/main/java/com/mycompany/app/numbers/Controller.java b/examples/webhooks/src/main/java/com/mycompany/app/numbers/Controller.java new file mode 100644 index 000000000..f898ce836 --- /dev/null +++ b/examples/webhooks/src/main/java/com/mycompany/app/numbers/Controller.java @@ -0,0 +1,78 @@ +package com.mycompany.app.numbers; + +import com.sinch.sdk.SinchClient; +import com.sinch.sdk.domains.numbers.api.v1.WebHooksService; +import com.sinch.sdk.domains.numbers.models.v1.webhooks.NumberEvent; +import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +@RestController("Numbers") +public class Controller { + + private final SinchClient sinchClient; + private final ServerBusinessLogic webhooksBusinessLogic; + + /** + * The secret value used for webhook calls validation have to equals to the one configured at + * number property (HmacSecret). + * + * @see update + * function Javadoc + */ + @Value("${numbers.webhooks.secret: }") + private String webhooksSecret; + + @Autowired + public Controller(SinchClient sinchClient, ServerBusinessLogic webhooksBusinessLogic) { + this.sinchClient = sinchClient; + this.webhooksBusinessLogic = webhooksBusinessLogic; + } + + @PostMapping( + value = "/NumbersEvent", + consumes = MediaType.APPLICATION_JSON_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity NumbersEvent( + @RequestHeader Map headers, @RequestBody String body) { + + WebHooksService webhooks = sinchClient.numbers().v1().webhooks(); + + // see https://developers.sinch.com/docs/numbers/api-reference/numbers/tag/Numbers-Callbacks for + // more information + // set this value to true to validate request from Sinch servers + boolean ensureValidAuthentication = false; + if (ensureValidAuthentication) { + // ensure valid authentication to handle request + var validAuth = + webhooks.validateAuthenticationHeader( + webhooksSecret, + // request headers + headers, + // request payload body + body); + + // token validation failed + if (!validAuth) { + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED); + } + } + + // decode the request payload + NumberEvent event = webhooks.parseEvent(body); + + // let business layer process the request + webhooksBusinessLogic.numbersEvent(event); + + return ResponseEntity.ok().build(); + } +} diff --git a/examples/webhooks/src/main/java/com/mycompany/app/numbers/ServerBusinessLogic.java b/examples/webhooks/src/main/java/com/mycompany/app/numbers/ServerBusinessLogic.java new file mode 100644 index 000000000..773b93310 --- /dev/null +++ b/examples/webhooks/src/main/java/com/mycompany/app/numbers/ServerBusinessLogic.java @@ -0,0 +1,16 @@ +package com.mycompany.app.numbers; + +import com.sinch.sdk.domains.numbers.models.v1.webhooks.NumberEvent; +import java.util.logging.Logger; +import org.springframework.stereotype.Component; + +@Component("NumbersServerBusinessLogic") +public class ServerBusinessLogic { + + private static final Logger LOGGER = Logger.getLogger(ServerBusinessLogic.class.getName()); + + public void numbersEvent(NumberEvent event) { + + LOGGER.info("Handle event: " + event); + } +} diff --git a/examples/webhooks/src/main/java/com/mycompany/app/sms/Controller.java b/examples/webhooks/src/main/java/com/mycompany/app/sms/Controller.java new file mode 100644 index 000000000..5b58c8150 --- /dev/null +++ b/examples/webhooks/src/main/java/com/mycompany/app/sms/Controller.java @@ -0,0 +1,80 @@ +package com.mycompany.app.sms; + +import com.sinch.sdk.SinchClient; +import com.sinch.sdk.domains.sms.api.v1.WebHooksService; +import com.sinch.sdk.domains.sms.models.v1.deliveryreports.DeliveryReport; +import com.sinch.sdk.domains.sms.models.v1.inbounds.InboundMessage; +import com.sinch.sdk.domains.sms.models.v1.webhooks.SmsEvent; +import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +@RestController("SMS") +public class Controller { + + private final SinchClient sinchClient; + private final ServerBusinessLogic webhooksBusinessLogic; + + @Value("${sms.webhooks.secret: }") + private String webhooksSecret; + + @Autowired + public Controller(SinchClient sinchClient, ServerBusinessLogic webhooksBusinessLogic) { + this.sinchClient = sinchClient; + this.webhooksBusinessLogic = webhooksBusinessLogic; + } + + @PostMapping( + value = "/SmsEvent", + consumes = MediaType.APPLICATION_JSON_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity smsEvent( + @RequestHeader Map headers, @RequestBody String body) { + + WebHooksService webhooks = sinchClient.sms().v1().webhooks(); + + // ensure valid authentication to handle request + // See + // https://developers.sinch.com/docs/sms/api-reference/sms/tag/Webhooks/#tag/Webhooks/section/Callbacks + // Contact your account manager to configure your callback sending headers validation or comment + // following line + // set this value to true to validate request from Sinch servers + // see https://developers.sinch.com/docs/numbers/api-reference/numbers/tag/Numbers-Callbacks for + // more information + boolean ensureValidAuthentication = false; + if (ensureValidAuthentication) { + var validAuth = + webhooks.validateAuthenticationHeader( + webhooksSecret, + // request headers + headers, + // request payload body + body); + + // token validation failed + if (!validAuth) { + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED); + } + } + + // decode the request payload + SmsEvent event = webhooks.parseEvent(body); + + // let business layer process the request + switch (event) { + case InboundMessage e -> webhooksBusinessLogic.processInboundEvent(e); + case DeliveryReport e -> webhooksBusinessLogic.processDeliveryReportEvent(e); + default -> throw new IllegalStateException("Unexpected value: " + event); + } + + return ResponseEntity.ok().build(); + } +} diff --git a/examples/webhooks/src/main/java/com/mycompany/app/sms/ServerBusinessLogic.java b/examples/webhooks/src/main/java/com/mycompany/app/sms/ServerBusinessLogic.java new file mode 100644 index 000000000..a8dd2c9b2 --- /dev/null +++ b/examples/webhooks/src/main/java/com/mycompany/app/sms/ServerBusinessLogic.java @@ -0,0 +1,25 @@ +package com.mycompany.app.sms; + +import com.sinch.sdk.domains.sms.models.v1.deliveryreports.DeliveryReport; +import com.sinch.sdk.domains.sms.models.v1.inbounds.InboundMessage; +import com.sinch.sdk.domains.sms.models.v1.webhooks.SmsEvent; +import java.util.logging.Logger; +import org.springframework.stereotype.Component; + +@Component("SMSServerBusinessLogic") +public class ServerBusinessLogic { + + private static final Logger LOGGER = Logger.getLogger(ServerBusinessLogic.class.getName()); + + public void processInboundEvent(InboundMessage event) { + trace(event); + } + + public void processDeliveryReportEvent(DeliveryReport event) { + trace(event); + } + + private void trace(SmsEvent event) { + LOGGER.info("Handle event: " + event); + } +} diff --git a/examples/webhooks/src/main/java/com/mycompany/app/verification/Controller.java b/examples/webhooks/src/main/java/com/mycompany/app/verification/Controller.java new file mode 100644 index 000000000..8f1acc637 --- /dev/null +++ b/examples/webhooks/src/main/java/com/mycompany/app/verification/Controller.java @@ -0,0 +1,94 @@ +package com.mycompany.app.verification; + +import com.sinch.sdk.SinchClient; +import com.sinch.sdk.domains.verification.api.v1.WebHooksService; +import com.sinch.sdk.domains.verification.models.v1.webhooks.VerificationRequestEvent; +import com.sinch.sdk.domains.verification.models.v1.webhooks.VerificationResultEvent; +import com.sinch.sdk.domains.verification.models.v1.webhooks.VerificationSmsDeliveredEvent; +import java.util.Map; +import java.util.logging.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +@RestController("Verification") +public class Controller { + + private static final Logger LOGGER = Logger.getLogger(Controller.class.getName()); + private final SinchClient sinchClient; + private final ServerBusinessLogic webhooksBusinessLogic; + + @Autowired + public Controller(SinchClient sinchClient, ServerBusinessLogic webhooksBusinessLogic) { + this.sinchClient = sinchClient; + this.webhooksBusinessLogic = webhooksBusinessLogic; + } + + @PostMapping( + value = "/VerificationEvent", + consumes = MediaType.APPLICATION_JSON_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity VerificationEvent( + @RequestHeader Map headers, @RequestBody String body) { + + WebHooksService webhooks = sinchClient.verification().v1().webhooks(); + + // ensure valid authentication to handle request + // set this value to true to validate request from Sinch servers + // see + // https://developers.sinch.com/docs/verification/api-reference/authentication/callback-signed-request + // for more information + boolean ensureValidAuthentication = false; + if (ensureValidAuthentication) { + var validAuth = + webhooks.validateAuthenticationHeader( + // The HTTP verb this controller is managing + "POST", + // The URI this controller is managing + "/VerificationEvent", + // request headers + headers, + // request payload body + body); + + // token validation failed + if (!validAuth) { + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED); + } + } + + // decode the request payload + var event = webhooks.parseEvent(body); + + // let business layer process the request + var response = + switch (event) { + case VerificationRequestEvent requestEvent -> + webhooksBusinessLogic.verificationEvent(requestEvent); + case VerificationResultEvent resultEvent -> { + webhooksBusinessLogic.verificationEvent(resultEvent); + yield null; + } + case VerificationSmsDeliveredEvent smsEvent -> { + webhooksBusinessLogic.verificationSmsDeliveredEvent(smsEvent); + yield null; + } + default -> throw new IllegalStateException("Unexpected value: " + event); + }; + + ResponseEntity responseEntity = ResponseEntity.ok().body(null); + + if (null != response) { + var serializedResponse = webhooks.serializeResponse(response); + LOGGER.finest("JSON response: " + serializedResponse); + responseEntity = ResponseEntity.ok(serializedResponse); + } + return responseEntity; + } +} diff --git a/examples/webhooks/src/main/java/com/mycompany/app/verification/ServerBusinessLogic.java b/examples/webhooks/src/main/java/com/mycompany/app/verification/ServerBusinessLogic.java new file mode 100644 index 000000000..203b7fa0f --- /dev/null +++ b/examples/webhooks/src/main/java/com/mycompany/app/verification/ServerBusinessLogic.java @@ -0,0 +1,36 @@ +package com.mycompany.app.verification; + +import com.sinch.sdk.domains.verification.models.v1.webhooks.VerificationEventResponseAction; +import com.sinch.sdk.domains.verification.models.v1.webhooks.VerificationRequestEvent; +import com.sinch.sdk.domains.verification.models.v1.webhooks.VerificationRequestEventResponse; +import com.sinch.sdk.domains.verification.models.v1.webhooks.VerificationRequestEventResponseSms; +import com.sinch.sdk.domains.verification.models.v1.webhooks.VerificationResultEvent; +import com.sinch.sdk.domains.verification.models.v1.webhooks.VerificationSmsDeliveredEvent; +import java.util.logging.Logger; +import org.springframework.stereotype.Component; + +@Component("VerificationServerBusinessLogic") +public class ServerBusinessLogic { + + private static final Logger LOGGER = Logger.getLogger(ServerBusinessLogic.class.getName()); + + public VerificationRequestEventResponse verificationEvent(VerificationRequestEvent event) { + + LOGGER.info("Handle event :" + event); + + // add your logic here according to SMS, FlashCall, PhoneCall, ... verification + return VerificationRequestEventResponseSms.builder() + .setAction(VerificationEventResponseAction.ALLOW) + .build(); + } + + public void verificationEvent(VerificationResultEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void verificationSmsDeliveredEvent(VerificationSmsDeliveredEvent event) { + + LOGGER.info("Handle event: " + event); + } +} diff --git a/examples/webhooks/src/main/java/com/mycompany/app/voice/Controller.java b/examples/webhooks/src/main/java/com/mycompany/app/voice/Controller.java new file mode 100644 index 000000000..b2eb3482d --- /dev/null +++ b/examples/webhooks/src/main/java/com/mycompany/app/voice/Controller.java @@ -0,0 +1,100 @@ +package com.mycompany.app.voice; + +import com.sinch.sdk.SinchClient; +import com.sinch.sdk.domains.voice.api.v1.WebHooksService; +import com.sinch.sdk.domains.voice.models.v1.webhooks.AnsweredCallEvent; +import com.sinch.sdk.domains.voice.models.v1.webhooks.DisconnectedCallEvent; +import com.sinch.sdk.domains.voice.models.v1.webhooks.IncomingCallEvent; +import com.sinch.sdk.domains.voice.models.v1.webhooks.NotificationEvent; +import com.sinch.sdk.domains.voice.models.v1.webhooks.PromptInputEvent; +import java.util.Map; +import java.util.logging.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +@RestController("Voice") +public class Controller { + + private final SinchClient sinchClient; + private final ServerBusinessLogic webhooksBusinessLogic; + private static final Logger LOGGER = Logger.getLogger(Controller.class.getName()); + + @Autowired + public Controller(SinchClient sinchClient, ServerBusinessLogic webhooksBusinessLogic) { + this.sinchClient = sinchClient; + this.webhooksBusinessLogic = webhooksBusinessLogic; + } + + @PostMapping( + value = "/VoiceEvent", + consumes = MediaType.APPLICATION_JSON_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity VoiceEvent( + @RequestHeader Map headers, @RequestBody String body) { + + WebHooksService webhooks = sinchClient.voice().v1().webhooks(); + + // ensure valid authentication to handle request + // set this value to true to validate request from Sinch servers + // see + // https://developers.sinch.com/docs/voice/api-reference/authentication/callback-signed-request + // for more information + boolean ensureValidAuthentication = false; + if (ensureValidAuthentication) { + // ensure valid authentication to handle request + var validAuth = + webhooks.validateAuthenticationHeader( + // The HTTP verb this controller is managing + "POST", + // The URI this controller is managing + "/VoiceEvent", + // request headers + headers, + // request payload body + body); + + // token validation failed + if (!validAuth) { + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED); + } + } + // decode the payload request + var event = webhooks.parseEvent(body); + + // let business layer process the request + var response = + switch (event) { + case IncomingCallEvent e -> webhooksBusinessLogic.incoming(e); + case AnsweredCallEvent e -> webhooksBusinessLogic.answered(e); + case DisconnectedCallEvent e -> { + webhooksBusinessLogic.disconnect(e); + yield null; + } + case PromptInputEvent e -> { + webhooksBusinessLogic.prompt(e); + yield null; + } + case NotificationEvent e -> { + webhooksBusinessLogic.notify(e); + yield null; + } + default -> throw new IllegalStateException("Unexpected value: " + event); + }; + + ResponseEntity responseEntity = ResponseEntity.ok().body(null); + + if (null != response) { + var serializedResponse = webhooks.serializeResponse(response); + LOGGER.finest("JSON response: " + serializedResponse); + responseEntity = ResponseEntity.ok(serializedResponse); + } + return responseEntity; + } +} diff --git a/examples/webhooks/src/main/java/com/mycompany/app/voice/ServerBusinessLogic.java b/examples/webhooks/src/main/java/com/mycompany/app/voice/ServerBusinessLogic.java new file mode 100644 index 000000000..4aedb702f --- /dev/null +++ b/examples/webhooks/src/main/java/com/mycompany/app/voice/ServerBusinessLogic.java @@ -0,0 +1,45 @@ +package com.mycompany.app.voice; + +import com.sinch.sdk.domains.voice.models.v1.svaml.SvamlControl; +import com.sinch.sdk.domains.voice.models.v1.webhooks.AnsweredCallEvent; +import com.sinch.sdk.domains.voice.models.v1.webhooks.DisconnectedCallEvent; +import com.sinch.sdk.domains.voice.models.v1.webhooks.IncomingCallEvent; +import com.sinch.sdk.domains.voice.models.v1.webhooks.NotificationEvent; +import com.sinch.sdk.domains.voice.models.v1.webhooks.PromptInputEvent; +import java.util.logging.Logger; +import org.springframework.stereotype.Component; + +@Component("VoiceServerBusinessLogic") +public class ServerBusinessLogic { + + private static final Logger LOGGER = Logger.getLogger(ServerBusinessLogic.class.getName()); + + public SvamlControl incoming(IncomingCallEvent event) { + + LOGGER.info("Handle event :" + event); + + return SvamlControl.builder().build(); + } + + public SvamlControl answered(AnsweredCallEvent event) { + + LOGGER.info("Handle event: " + event); + + return SvamlControl.builder().build(); + } + + public void disconnect(DisconnectedCallEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void prompt(PromptInputEvent event) { + + LOGGER.info("Handle event: " + event); + } + + public void notify(NotificationEvent event) { + + LOGGER.info("Handle event: " + event); + } +} diff --git a/examples/webhooks/src/main/resources/application.yaml b/examples/webhooks/src/main/resources/application.yaml new file mode 100644 index 000000000..493ab739d --- /dev/null +++ b/examples/webhooks/src/main/resources/application.yaml @@ -0,0 +1,49 @@ +# springboot related config file + +logging: + level: + com: INFO + +server: + port: 8090 + +# only required if you need to call any Sinch services when processing webhooks +credentials: + # Java SDK domains supporting unified credentials + # - Numbers + # - SMS: US/EU are the only supported regions with unified credentials + # - Conversation + project-id: + key-id: + key-secret: + + # Application related credentials, used by: + # - Verification + # - Voice + application-api-key: + application-api-secret: + +numbers: + webhooks: + # Secret value set for Numbers webhooks calls validation + # Used when "ensureValidAuthentication" within [Controller.java](../java/com/mycompany/app/numbers/Controller.java) is set to true + secret: + +conversation: + # Sets the region for Conversation + # See https://github.com/sinch/sinch-sdk-java/blob/main/client/src/main/com/sinch/sdk/models/ConversationRegion.java for list of supported values + region: + webhooks: + # Secret value set for Conversation webhooks calls validation + # Used when "ensureValidAuthentication" within [Controller.java](../java/com/mycompany/app/conversation/Controller.java) is set to true + secret: + +sms: + # Sets the region for SMS + # valid values are "us" and "eu" + # See https://github.com/sinch/sinch-sdk-java/blob/main/client/src/main/com/sinch/sdk/models/SMSRegion.java for full list of supported values but with servicePlanID + region: + webhooks: + # Secret value set for Sms webhooks calls validation + # Used when "ensureValidAuthentication" within [Controller.java](../java/com/mycompany/app/sms/Controller.java) is set to true + secret: