Send and Receive sms through Java in RingCentral - ringcentral

I am quite new to the ringcentral APIs and currently going through all of them.
Currently going through the following reference: https://developers.ringcentral.com/api-reference/SMS/createSMSMessage
Through Java we can use an API to send SMS, but can we receive a SMS using Java.
Can someone help me in getting the documentation/article or any kind of reference where I can get to know the simple way to send and receive the SMS using Java

A sample send SMS example with Java as follows:
import java.io.IOException;
import com.ringcentral.*;
import com.ringcentral.definitions.*;
public class Send_SMS {
String RECIPIENT_NUMBER = "<ENTER PHONE NUMBER>";
String RINGCENTRAL_CLIENTID = "<ENTER CLIENT ID>";
String RINGCENTRAL_CLIENTSECRET = "<ENTER CLIENT SECRET>";
String RINGCENTRAL_USERNAME = "<YOUR ACCOUNT PHONE NUMBER>";
String RINGCENTRAL_PASSWORD = "<YOUR ACCOUNT PASSWORD>";
String RINGCENTRAL_EXTENSION = "<YOUR EXTENSION, PROBABLY ";
public static void main(String[] args) {
var obj = new Send_SMS();
try {
obj.sendSms();
} catch (RestException | IOException e) {
e.printStackTrace();
}
}
public void sendSms() throws RestException, IOException{
RestClient rc = new RestClient(RINGCENTRAL_CLIENTID, RINGCENTRAL_CLIENTSECRET, RINGCENTRAL_SERVER);
rc.authorize(RINGCENTRAL_USERNAME, RINGCENTRAL_EXTENSION, RINGCENTRAL_PASSWORD);
CreateSMSMessage postParameters = new CreateSMSMessage();
postParameters.from = new MessageStoreCallerInfoRequest().phoneNumber(RINGCENTRAL_USERNAME);
postParameters.to = new MessageStoreCallerInfoRequest[]{new MessageStoreCallerInfoRequest().phoneNumber(RECIPIENT_NUMBER)};
postParameters.text = "Hello World from Java";
var response = rc.restapi().account().extension().sms().post(postParameters);
System.out.println("SMS sent. Message status: " + response.messageStatus);
}
}
You can download the java SDK from here: https://github.com/ringcentral/ringcentral-java
and start with documentation here: https://developers.ringcentral.com/guide/messaging/quick-start/java
Once you get the library in your application, you can start compiling it and running it.

Here is a SMS Java quickstart guide: https://developers.ringcentral.com/guide/sms/quick-start/java
Hope this helps!

Here is the official RingCentral Java SDK: https://github.com/ringcentral/ringcentral-java, it is currently 1.0.0-beta9. We are going to release a stable version this month.
Here is a list of all the API calls that you can invoke: https://github.com/ringcentral/ringcentral-java/blob/master/samples.md, including sms sending: https://github.com/ringcentral/ringcentral-java/blob/master/samples.md#create-smsmms-message
For sms receiving, you can use our subscription and notification feature: https://github.com/ringcentral/ringcentral-java#pubnub-subscriptions--notificatioins
So whenever there is new sms, you will be notified, then you can issue api call to get the message.
For technical details, you can always send email to devsupport#ringcentral.com

Related

ASP.Net Core XUnit Integration Testing when Two Factor Authenication is enabled

I've developing an Angular web application using ASP.Net Core 3.1 for the API.
So far, I've written some integration unit tests using a Custom WebApplicationFactory to create the test server.
All tests use the HttpClient to make GETs and POSTs to the API running under the Custom WebApplicationFactory. Most of these tests initially perform a login to obtain a token to use for subsequent requests.
I'd like to add Two Factor Authentication to the application, but this will inevitably break any tests, as they aren't able to get hold of the six digit code which would be sent via email.
Here is what a test currently looks like, without MFA being implemented.
Is there a way that the test can be given the MFA code so that it can continue to perform tests?
Do I simply need to seed a user that does not have MFA enabled?
I actually want all users to have MFA enabled in production.
Many thanks
using Xunit;
using System.Threading.Tasks;
using MyCompany.ViewModels.Authentication;
using MyCompany.StaffPortal.Tests.Shared;
using StaffPortal;
using Newtonsoft.Json;
using MyCompany.ServiceA.ViewModels;
using System.Collections.Generic;
using System.Net.Http;
namespace MyCompany.Tests.StaffPortal.ServiceA
{
public class ExtensionsControllerTests : TestBase
{
public ExtensionsControllerTests(CustomWebApplicationFactory<Startup> factory) : base(factory)
{
}
[Fact]
public async Task Test_GetExtensions()
{
//This line creates a new "web browser" and uses the login details provided to obtain and set up the token so that we can request information about an account.
HttpClient httpClient = await CreateAuthenticatedHttpClient("abcltd1#MyCompany.com", "test", 1);
//Perform any work and get the information from the API
//Contact the API using the token so check that it works
var getExtensionsResponse = await httpClient.GetAsync("/api/ServiceA/extensions/GetExtensions");
//Check that the response was OK
Assert.True(getExtensionsResponse.StatusCode == System.Net.HttpStatusCode.OK, "GetExtensions did not return an OK result.");
//Get and Convert the Content we received into a List of ServiceAExtensionViewModel, as that is what GetExtensions sends back to the browser.
var getExtensionsResponseContent = await getExtensionsResponse.Content.ReadAsStringAsync();
List<ServiceAExtensionViewModel> extensionList = JsonConvert.DeserializeObject<List<ServiceAExtensionViewModel>>(getExtensionsResponseContent);
//Check the information received matches our expectations
Assert.True(extensionList.Count == 2);
Assert.True(extensionList[0].PropertyA == 123);
Assert.True(extensionList[0].PropertyB == 0161);
Assert.True(extensionList[0].PropertyC == true);
}
}
}
Here is the content's of CreateAuthenticatedHttpClient() for reference.
protected async Task<HttpClient> CreateAuthenticatedHttpClient(string username, string password, int companyAccountId)
{
var httpClient = _factory.CreateClient(
new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
//Create the Login information to send to the server
var loginInformation = new LoginRequestModel
{
Username = username,
Password = password,
ReturnUrl = ""
};
//Convert it into Json which the server will understand
var validLoginRequestJson = ConvertToJson(loginInformation);
//Send the Json Login information to the server, and put the response we receive into loginResponse
//In the code below, httpClient is like a web browser. You give it the
var loginResponse = await httpClient.PostAsync("/api/authenticate", validLoginRequestJson);
//Check the loginResponse was a CREATED response, which means that the token was made
Assert.True(loginResponse.StatusCode == System.Net.HttpStatusCode.Created, "New Token was not returned.");
//Check the response is identified as being in Json format
Assert.Equal("application/json; charset=utf-8", loginResponse.Content.Headers.ContentType.ToString());
//Next we have to convert the received Json information into whatever we are expecting.
//In this case, we are expecting a AuthenticationResponseViewModel (because that's what the API sends back to the person trying to log in)
//First we get hold of the Content (which is in Json format)
var responseJsonString = await loginResponse.Content.ReadAsStringAsync();
//Second we convert the Json back into a real AuthenticationResponseViewModel
AuthenticationResponseViewModel authenticationResponseViewModel = JsonConvert.DeserializeObject<AuthenticationResponseViewModel>(responseJsonString);
//Now we take the Token from AuthenticationResponseViewModel, and add it into the httpClient so that we can check the Token works.
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authenticationResponseViewModel.token);
httpClient.DefaultRequestHeaders.Add("CompanyId", companyAccountId.ToString());
return httpClient;
}

How do I register Google Classroom API for push notifications?

I want to create a program that will receive notifications from my Google Classroom in question, and do something with that data. How can I register Google Classroom to react to an event?
I haven't made anything yet, and I don't know anything about Google's APIs. What should I do?
The process of registering the Google Classroom API for push notifications includes authentication, authorization, and parsing a request to Google to tell your Classroom to send these push notifications.
I highly recommend you have basic knowledge of the Google Cloud platform in the Java programming language, unlike me when I tried to do this. Trust me... it wasn't fun.
I do believe you will understand this concept enough to be able to transfer it to your language of choice, I did this in Java, using IntelliJ IDEA as my IDE.
Apart from the Google Classroom API, Google features another service to their collection called "Pub/Sub". Pub/Sub stands for Publisher/Subscriber. If you're familiar with how a queue works, think of Pub/Sub as a sort of refined queue system. You have a publisher, who posts messages on a "topic", and a subscriber to the topic who will pull messages from the topic, and choose to "acknowledge" the message or not. Acknowledging a message deletes it from the queue. For example, the publisher code sends the message "Hello, World" to a topic. That message will stay in the topic until a subscriber to that topic chooses to pull the message, read "Hello, World", and acknowledge the message, so it doesn't pop up again when pulling messages. The publisher can send as many messages as it wants. The publisher can send 10 messages, and the subscriber can choose to pull them all and iterate through them or just a few at a time.
This applies to this system because you're going to use a built-in function of the Google Classroom API that allows the API to act as a "publisher" and send update messages to a topic of your choosing. Then, you'll have a separate application checking for updates whenever you'd wish. To simplify it for now, you tell the Classroom API to "Please send update messages to this topic. I only want updates when the teacher edits the course work catalog in any way". This request will be followed by the Classroom API and the program will send messages to your topic whenever a teacher edits, or posts, or deletes, and such more.
If your classroom publisher sent 5 updates in a day, you'll have 5 pullable messages sent to your topic that any subscribing program of that topic can pull and acknowledge.
If you do not understand enough, in your opinion. Please, please do some research on Google Cloud Pub/Sub before continuing, since doing this basically revolves around this service.
Let's do this step-by-step...
Create a new project
Enable Classroom API and PubSub API
Enable Billing
Go to "IAM & admin"
Give the owner permission to "classroom-notifications#system.gserviceaccount.com"
Set up credentials for Classroom API and a "UI-based platform" using "User data"
Set up the consent screen. Just add an application name for now.
Create credentials as an "OAuth Client ID"
Choose Application Type > Other. Don't mind the client name
Download the JSON file. Rename it to "credentials_temp.json"
Create a Gradle based Java project (I'm using IntelliJ). Group id: temp. Artifact id: temp. Project name: temp
Add this to build.gradle under "dependencies"
compile 'com.google.api-client:google-api-client:1.23.0'
compile 'com.google.oauth-client:google-oauth-client-jetty:1.23.0'
compile 'com.google.apis:google-api-services-classroom:v1-rev135-1.23.0'
Set the sourceCompatibility variable in build.gradle to 11
Import those changes (There may be a little box at the bottom-right saying "import changes" as an option)
Put the credentials file in src/main/resources
In src/main/java, make a new class. Name it "TempTest.java"
Use this code I've written for you
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.classroom.Classroom;
import com.google.api.services.classroom.model.*;
import java.io.*;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;
import static com.google.api.services.classroom.ClassroomScopes.all;
public class TempTest {
private static final String APPLICATION_NAME = "Google Classroom API Java Quickstart";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = "tokens";
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
private static List<String> SCOPES = new ArrayList<>();
private static Classroom service;
private static String TOPIC_NAME = "projects/temp-260404/topics/temp";
private static String COURSE_ID = "47737005203";
static {
SCOPES.addAll(all());
}
public static void main(String... args) throws IOException, GeneralSecurityException {
final var HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
service = buildClassroomService(HTTP_TRANSPORT);
// registerForPushNotifications();
List<Course> courses = getAllCourses();
if (courses == null || courses.size() == 0)
System.out.println("No courses found.");
else {
System.out.println("\nCourses:");
for (var currentCourse : courses)
System.out.println(currentCourse.getName() + "(" + currentCourse.getId() + ")");
}
}
private static void registerForPushNotifications() throws IOException {
final var pubSupTopic = new CloudPubsubTopic()
.setTopicName(TOPIC_NAME);
final var courseWorkChangesInfo = new CourseRosterChangesInfo()
.setCourseId(COURSE_ID);
final var feed = new Feed()
.setFeedType("COURSE_WORK_CHANGES")
.set("courseWorkChangesInfo", courseWorkChangesInfo);
Registration notificationsRegistration = new Registration()
.setFeed(feed)
.setCloudPubsubTopic(pubSupTopic);
pubSupTopic.setFactory(JSON_FACTORY);
courseWorkChangesInfo.setFactory(JSON_FACTORY);
feed.setFactory(JSON_FACTORY);
notificationsRegistration.setFactory(JSON_FACTORY);
service.registrations().create(notificationsRegistration).execute();
System.out.println("Successfully registered");
}
private static Classroom buildClassroomService(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
final var serviceCredentials = getCredentials(HTTP_TRANSPORT);
return new Classroom.Builder(HTTP_TRANSPORT, JSON_FACTORY, serviceCredentials)
.setApplicationName(APPLICATION_NAME)
.build();
}
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
final var clientSecrets = loadJSONClientSecrets();
final var dataStoreFactory = new FileDataStoreFactory(new File(TOKENS_DIRECTORY_PATH));
final var authenticationFlow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(dataStoreFactory)
.setAccessType("offline")
.build();
return redirectToAuthentication(authenticationFlow);
}
private static GoogleClientSecrets loadJSONClientSecrets() throws IOException {
final var credentialFileStream = getCredentialsJSONFile();
if (credentialFileStream == null)
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
return GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(credentialFileStream));
}
private static InputStream getCredentialsJSONFile() {
return TempTest.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
}
private static Credential redirectToAuthentication(GoogleAuthorizationCodeFlow flow) throws IOException {
final var receiver = new LocalServerReceiver.Builder().setPort(8888).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
private static List<Course> getAllCourses() throws IOException {
ListCoursesResponse response = service.courses().list()
.execute();
return response.getCourses();
}
}
Go to Google Classroom and create your own Classroom for testing purposes.
Go to Pub/Sub and create a new topic. Make sure it's set to "Google managed key". Get its name under "Topic name" when it's made. There is a little button for copying the full path.
Set the TOPIC_NAME field of the class to a String containing the topic name you just copied
Run the code and authorize with all scopes. You will be redirected. Make sure you choose the same account you use Cloud Platform on.
Running it will give you a list of your courses and their ID numbers in parentheses. Copy the ID number of the test course you made. It should be outputted to the console after running your code.
Set the COURSE_ID field of the class to a String containing the ID you just copied
Uncomment line 40 and run the code again
You're done with my example
What you just did was authenticate yourself so Google Knows what permissions you're giving it, and it can verify your identity. Then, you sent a JSON request to Google with information about what topic you want updates to be published to, the type of updates to get, and the specific classroom to get these updates from.
I highly, HIGHLY recommend you learn how the structure of the JSON response works here.
Perhaps start here.
This page on the Google documentation has decent information. It also shows the JSON formatting of the message you'll pull from another program using the Google Pub/Sub API. I have not included that here.
Thank you, and good luck. Sorry, I may edit this question a few times. I'm really tired right now.

how to send voice from lex bot to lambda using java in aws

I can able to send the text to my lambda function from lex bot and getting the response. But how to send the voice from bot to lambda and getting a response in voice or text format. Please suggest.
The following blog written by AWS engineering team will definitely by helpful to address your problem.
https://aws.amazon.com/blogs/machine-learning/capturing-voice-input-in-a-browser/
Following lambda function code returns voice from Bot.
`public Object handleRequest(Map<String,Object> input, Context context) {
context.getLogger().log("input" +input);
LexRequest lexRequest = LexRequestFactory.createLexRequest(input);
String content = String.format("<speak>Hi! Request came from:"+lexRequest.getBotName()+"</speak>",
lexRequest.getIntentName(),lexRequest.getCrust(),lexRequest.getPizzaKind(),lexRequest.getSize()
);
SessionAttributes sessionAttributes = new SessionAttributes();
Message message = new Message("SSML",content);
DialogAction dialogAction = new DialogAction("Close", "Fulfilled", message);
return new LexRespond(sessionAttributes,dialogAction);
}`

sending sms from java web app using aws sns

A user will create an account on my web app. The app will need to authenticate the user by sending a text message to the mobile phone number that the user provides. The text message is a short unique code, which the user will need to type in to the web browser in order for the app to authenticate the user.
How can I configure Amazon AWS SNS for this use case?
From what I have read, SNS works by the webmaster selecting a topic and then each user subscribes to that topic. Then the webmaster sends messages broadcast style to all the subscribers to the topic. This would not meet my requirements of sending a unique message to each user. Alternatively, creating a separate topic for every phone number would be too cumbersome, not to mention creating security issues with respect to protecting the privacy of all the phone numbers.
Can Amazon AWS SNS be configured for this use case? If so, how?
I am using Java.
SNS topics are only nedded when you need to send a SMS message to multiple mobile numbers. If you want to send a SMS message to a single number you can use the Amazon AWS SDK.
Docs are available at http://docs.aws.amazon.com/sns/latest/dg/sms_publish-to-phone.html#sms_publish_sdk.
Example code:
public static void main(String[] args) {
AWSCredentials awsCredentials = new BasicAWSCredentials("YOUR_Client_ID", "YOUR_Client_secret");
final AmazonSNSClient client = new AmazonSNSClient(awsCredentials);
client.setRegion(Region.getRegion(Regions.REGION_YOU_WANT_TO_USE));
AmazonSNSClient snsClient = new AmazonSNSClient(awsCredentials);
String message = "My SMS message";
String phoneNumber = "+1XXX5550100";
Map<String, MessageAttributeValue> smsAttributes =
new HashMap<String, MessageAttributeValue>();
//<set SMS attributes>
sendSMSMessage(snsClient, message, phoneNumber, smsAttributes);
}
public static void sendSMSMessage(AmazonSNSClient snsClient, String message,
String phoneNumber, Map<String, MessageAttributeValue> smsAttributes) {
PublishResult result = snsClient.publish(new PublishRequest()
.withMessage(message)
.withPhoneNumber(phoneNumber)
.withMessageAttributes(smsAttributes));
System.out.println(result); // Prints the message ID.
}
Remember to create an user on IAM console adding a permission to access the SNS Service. You need to add AmazonSNSFullAccess role.
Replace YOUR_Client_ID and YOUR_Client_secret with user credentials you have created.
Some methods have been deprecated in AWS SDK.
BasicAWSCredentials awsCredentials = new BasicAWSCredentials("CLIENT-ID", "SECRET-KEY");
AmazonSNS snsClient = AmazonSNSClientBuilder.standard()
.withRegion(Regions.fromName("YOUR_REGION"))
.withCredentials(new AWSStaticCredentialsProvider(awsCredentials)).build();
Map<String, MessageAttributeValue> smsAttributes = new HashMap<String, MessageAttributeValue>();
smsAttributes.put("AWS.SNS.SMS.SenderID",new MessageAttributeValue().withStringValue("SENDER-ID").withDataType("String"));
smsAttributes.put("AWS.SNS.SMS.SMSType",new MessageAttributeValue().withStringValue("Transactional").withDataType("String"));
PublishRequest request = new PublishRequest();
request.withMessage("YOUR MESSAGE")
.withPhoneNumber("E.164-PhoneNumber")
.withMessageAttributes(smsAttributes);
PublishResult result=snsClient.publish(request);
Sending an SMS using the AWS SDK for Java:
public static void main(String[] args) {
AmazonSNSClient snsClient = new AmazonSNSClient();
String message = "My SMS message";
String phoneNumber = "+1XXX5550100";
Map<String, MessageAttributeValue> smsAttributes =
new HashMap<String, MessageAttributeValue>();
//<set SMS attributes>
sendSMSMessage(snsClient, message, phoneNumber, smsAttributes);
}
public static void sendSMSMessage(AmazonSNSClient snsClient, String message,
String phoneNumber, Map<String, MessageAttributeValue> smsAttributes) {
PublishResult result = snsClient.publish(new PublishRequest()
.withMessage(message)
.withPhoneNumber(phoneNumber)
.withMessageAttributes(smsAttributes));
System.out.println(result); // Prints the message ID.
}
For this particular use case you should consider the AWS Customer Engagement Service Amazon Pinpoint. It allows sending SMS, emails and push notifications, with tools for marketing campaigns as well as analytics:
Amazon Pinpoint Developer Guide
The documentation includes a tutorial for your specific use case:
Setting Up an SMS Registration System Using Amazon Pinpoint
For what you described, while it could be done using SNS with the AWS SDK for Java, Pinpoint is designed to interact with application users, so it's probably a better alternative
Individual SMS/MMS messaging is outside the apparent use cases of AWS SNS.
If you need to send proper SMS/MMS text messages to arbitrary phone numbers, you'll need to turn to other platforms, such as Twilio or Bandwidth.

Automationg AdvancedRestClient Extension for chrome

Hi I am trying to automate AdvancedRestClient extension for Chrome to test webservice.
I am able to start the Extension and send request. But I am not able to get any response.
public class WebServices {
public static void main(String[] args) {
//Start the driver
System.setProperty("webdriver.chrome.driver","$PATH_TO_DRIVER");
ChromeOptions options = new ChromeOptions();
options.addArguments("load-extension=C:/Users/$username/AppData/Local/Google/Chrome/User Data/Default/Extensions/hgmloofddffdnphfgcellkdfbfbjeloo/3.1.7_0");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
ChromeDriver driver = new ChromeDriver(capabilities);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
//Start the extension
driver.get("chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo/RestClient.html");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Get the authentication field and set authentication
WebElement authField = driver.findElement(By.xpath("//*[#id='appContainer']/div/div/div/div[4]/div[2]/section[1]/textarea"));
authField.sendKeys("$SET_AUTORIZATION")
//Get the reqestURL field and enter request
WebElement requestField = driver.findElement(By.xpath("//*[#id='appContainer']/div/div/div/div[2]/input"));
requestField.clear();
requestField.sendKeys("$REQUEST");
authField.click();
//Click on send button
WebElement sendButton = driver.findElement(By.xpath("//*[#id='appContainer']/div/div/div/div[7]/div/button[2]"));
sendButton.click();
}
}
The above steps work fine when I do it manually. But script does not generate any response.
Please help.
Automating a browser to test a web service is not the most reliable or efficient way.
You should instantiate a HttpClient in your test instead a Webdriver instance. This will allow you to make REST calls directly and interogate the response in the same way you would assert via WebDriver.
This approach will take milliseconds rather than seconds to run a test. Also, it can run anywhere without the need to install Chrome or Webdriver