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 f167ffde7..031f83d88 100755 --- a/examples/compile.sh +++ b/examples/compile.sh @@ -1,4 +1,10 @@ #!/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 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/webhooks/src/main/java/com/mycompany/app/numbers/Controller.java b/examples/webhooks/src/main/java/com/mycompany/app/numbers/Controller.java index 3c1637c87..f898ce836 100644 --- a/examples/webhooks/src/main/java/com/mycompany/app/numbers/Controller.java +++ b/examples/webhooks/src/main/java/com/mycompany/app/numbers/Controller.java @@ -47,9 +47,9 @@ public ResponseEntity NumbersEvent( WebHooksService webhooks = sinchClient.numbers().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 + // set this value to true to validate request from Sinch servers boolean ensureValidAuthentication = false; if (ensureValidAuthentication) { // ensure valid authentication to handle request diff --git a/examples/webhooks/src/main/resources/application.yaml b/examples/webhooks/src/main/resources/application.yaml index e5d52fe30..493ab739d 100644 --- a/examples/webhooks/src/main/resources/application.yaml +++ b/examples/webhooks/src/main/resources/application.yaml @@ -23,17 +23,19 @@ credentials: application-api-key: application-api-secret: -# Secret value set for Numbers webhooks calls validation 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: -# Secret value set for Conversation webhooks calls validation 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: @@ -42,4 +44,6 @@ sms: # 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: