Unclear how to connect Plivo to OpenTok Java SDK SIP - java

I'm trying to use Plivo with the OpenTok Java SDK to dial out. There is an example for javascript where Plivo is used.
I'm able to invoke the method Openok.dial() and get a positive response that I then send to my react client.
There are no errors but I'm not calling the targeted number.
I'm not understanding how to use the uris or if they are still necessary.
So is it still necessary to create the uri's as stated in the JS example (https://github.com/opentok/opentok-sip-samples/tree/master/Plivo-SIP-Dial-Out)? And how do i then use those uri's?
Or is there an example i can peek to get a rough idea?

TokBox Developer Evangelist here.
The OpenTok SIP Interconnect feature allows you dial out to a SIP address (uri). With the Plivo sample, you would have to create an application on their website and configure the Plivo application with the appropriate webhooks so when that when you dial out to the Plivo SIP uri from OpenTok, you will get events on the webhook which will allow you to connect the OpenTok session with the PSTN user.
You can also leverage Nexmo or other SIP providers to dial out and connect an OpenTok session with a PSTN user. For example, if you use Nexmo, you can dial directly to a phone number by constructing the SIP properties in the OpenTok Java SDK like so:
String nexmoApiKey = "";
String nexmoApiSecret = "";
String sessionId = "";
String token = "";
SipProperties properties = new SipProperties.Builder()
.sipUri("sip:15555555555#sip.nexmo.com")
.from("from#example.com")
.headersJsonStartingWithXDash(headerJson)
.userName(nexmoApiKey)
.password(nexmoApiSecret)
.secure(false)
.build();
Sip sip = opentok.dial(sessionId, token, properties);
Please note that you would have to configure the phoneNumber, sessionId, token, and credentials - I've just added a sample number along with empty strings as the credentials.

Related

Read email from office365 inbox without using of IMAP and POP3

There is a need to read email from office365 inbox without using of IMAP and POP3 protocol, Because these protocols are disabled in my case and also I can't enable them due to some security issue. Please suggest me if any other way to do the same without these two protocol.
Thanks in advance!
Yes there is another way (several in fact, but I will suggest one). There is an API called EWS (Exchange Web Services). It is pretty straightforward to use. You just need the Credentials of the account.
Here is a small example:
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2); // This is the latest version of this library
ExchangeCredentials credentials = new WebCredentials("email", "password");
service.setCredentials(credentials);
// this.exchangeService.setWebProxy(new WebProxy("xx.xxx.xxx.xx", 8080)); // If you're behind a proxy
service.setUrl(new URI("https://outlook.office365.com/EWS/Exchange.asmx")); // This is the standard URL
Folder inboxFolder = Folder.bind(service, WellKnownFolderName.Inbox);
FindItemsResults<Item> results = service.findItems(inboxFolder.getId(), new ItemView(10)); // 10 is the number of items to fetch (pagesize)
for (Item result : results)
{
EmailMessage currentEmail = (EmailMessage) result;
System.out.println(currentEmail.getFrom());
// And so on
}
The library is capable of doing a lot more such as reading/booking appointments, sending Emails, and so on.
The library uses SOAP as far as my knowledge goes, so you're safe from POP and IMAP.

Using Gmail aliases to link mail replies to application content

I have the following use case in my app:
When a specific event happens in the app all interested users should be notified by email. Then if a user replies to the email, his reply should be shown in the event page in the app.
My initial idea was to create a temp mail alias of the main notification email every time when an event happens and send the notification email with that alias set in the Reply-To header. Then if someone replies to that mail by using the alias (let's say csa123423#mydomain.com) I can figure out which event this reply refers to.
It turned out that Spring's JavaMailSender doesn't provide a way to use aliases, so I tried with Gmail API. As far as I understood creating a Gmail alias means actually setting an already existing email in your domain as an alias for another already existing email in that domain. So the Java code to achieve this using Directory API and Gmail API would look like this:
User newUser = new User();
UserName userName = new UserName();
userName.setGivenName("xsd");
userName.setFamilyName("ewrewr");
newUser.setPrimaryEmail("bbb34262bb45#mydomain.com");
newUser.setPassword("12345");
newUser.setName(userName);
User result = directoryService.users().insert(newUser).execute();
SendAs sendAs = new SendAs().setSendAsEmail("bbb34262bb45#mydomain.com").setReplyToAddress("bbb34262bb45#mydomain.com").setDisplayName("My name").setTreatAsAlias(true);
SendAs sendAsResult = gmailService.users().settings().sendAs().create(user, sendAs).execute();
MimeMessage emailContent = createEmail("mymail#gmail.com", "bbb34262bb45#mydomain.com", "Test from app", "Test body");
Message message = createMessageWithEmail(emailContent);
message = gmailService.users().messages().send(user, message).execute();
But as far as I know there are some limits on the number of accounts you can create per domain/account and also Google would charge more for this.
Is there another easier way to create aliases in Gmail? Or is there another approach to achieve the desired functionality (linking mail replies to application content) without using mail aliases?
Try leveraging '+' functionality given by Gmail for creating temporary aliases.
The basic idea is if my email id is xyz#gmail.com, I can send/receive an email with xyz+1#gmail.com or xyz+anything_here#gmail.com and it will work like a charm.
You can utilize this by keeping the alias/unique-id after the '+' in the Gmail id and then parse this alias easily in your application.

Microsoft Translator API Java, How to get client new ID with Azure

Translate.setClientId("something");
Translate.setClientSecret("something1");
I had previously ran my code successfully using the following syntax, however, 50% of the time I will get an error saying: TranslateApiException: Cannot find an active Azure Market Place Translator Subscription associated with the request credentials. :
I had my app subscribed with the OLD website that Microsoft was using, but I think the problem is occurring because they are using Azure. Now, I have my app subscribed with Azure, I have a subscription for the Microsoft Translator API services. Was wondering how to set this to the NEW ClientID, ClientSecret that Azure provides.
This is the "old" site that I subscribed through first:
https://datamarket.azure.com/home/
As the information from the old offical site(for translator speech & text api) & Announcements said, "THE MICROSOFT TRANSLATOR API IS NOW AVAILABLE ON THE AZURE PORTAL" and "Action Required before April 30, 2017 - Microsoft Translator Moves to Azure". So if you want to use the Translator API now, you need to have an Azure subscription and create a Translator account of Azure Cognitive service like the offical tutorial said.
For example using Translator Text API, you can follow the new tutorial to get an access token to build an appid for the API like my sample code in Java below.
// Get the access token
// The key got from Azure portal, please see https://learn.microsoft.com/en-us/azure/cognitive-services/cognitive-services-apis-create-account
String key = "<your translator account key>";
String authenticationUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
HttpsURLConnection authConn = (HttpsURLConnection) new URL(authenticationUrl).openConnection();
authConn.setRequestMethod("POST");
authConn.setDoOutput(true);
authConn.setRequestProperty("Ocp-Apim-Subscription-Key", key);
IOUtils.write("", authConn.getOutputStream(), "UTF-8");
String token = IOUtils.toString(authConn.getInputStream(), "UTF-8");
System.out.println(token);
// Using the access token to build the appid for the request url
String appId = URLEncoder.encode("Bearer "+token, "UTF-8");
String text = URLEncoder.encode("happy birthday", "UTF-8");
String from = "en";
String to = "fr";
String translatorTextApiUrl = String.format("https://api.microsofttranslator.com/v2/http.svc/Translate?appid=%s&text=%s&from=%s&to=%s", appId, text, from, to);
HttpsURLConnection translateConn = (HttpsURLConnection) new URL(translatorTextApiUrl).openConnection();
translateConn.setRequestMethod("GET");
translateConn.setRequestProperty("Accept", "application/xml");
String resp = IOUtils.toString(translateConn.getInputStream(), "UTF-8");
System.out.println(resp);
Hope it helps. Any concern, please feel free to let me know.
You can to sign in through https://www.microsoft.com/cognitive-services
Then, you'll find a list of keys for all services under cognitive services:

How to validate Twitter OAuth credentials (including email) in a Java server

I have a client/server game (iOS client, Java server) in which player accounts are tied to email addresses. The client allows sign-in with Google, Facebook and Twitter, using their respective sign-in SDKs.
To prevent clients from spoofing the wrong email address, I validate the oauth tokens by sending them over SSL to the server side, and using the user's credentials to validate that they do indeed own that email address.
For Google and Facebook, token validation (and fetching the associated email) was a pretty straightforward REST call. But Twitter requires you to create a signed request, which turns out to be complex and error-prone. Fortunately there is an open-source client library, twitter4j, which enabled me to do it in just a few lines of code.
Figuring out how to use twitter4j for this task was a bit tricky, so I'm documenting it here.
You'll need these imports:
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
When you sign up your app for Twitter API access, they provide you a consumer API key and a consumer API secret to identify your iOS app. You will need these available on your Java server somehow. It is easiest to put them directly into the source code:
String consumerApiKey = "arglebarglearglebargle"; // oauth_consumer_key
String consumerApiSecret = "tHiSisas3cReTc0nSUm3rAp1Keypr0v1d3Dbytw1tt3r";
Then you need your oauth credentials sent over from the iOS app:
String accessToken = "myUs3rs0aUthAcc355t0k3n";
String accessTokenSecret = "sdflkjasdflkjasdlfkjasdlfkjasldkfjlasdkfjldf";
Configure twitter4j with your credentials:
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerApiKey);
builder.setOAuthConsumerSecret(consumerApiSecret);
builder.setOAuthAccessToken(accessToken);
builder.setOAuthAccessTokenSecret(accessTokenSecret);
builder.setIncludeEmailEnabled(true);
Configuration config = builder.build();
TwitterFactory factory = new TwitterFactory(config);
Twitter twitter = factory.getInstance();
Now you can make Twitter API calls via the Twitter object. In my case, I make a single call to verify the oauth credentials and fetch the user's email so I can check it against the player database:
twitter4j.User user = twitter.verifyCredentials();
String email = user.getEmail();
...

How to access Bitbucket API from a Java Desktop App via Jersey+Oltu?

As the title states it, I want to access the bitbucket API from a native Java Desktop Application. Bitbucket requires Applications to use OAuth2, and for that I found that Oltu should do the job.
However, my knowledge of OAuth is very limited and so I am stuck at a very early point. Here is what I did so far:
Step 1: I registered an OAuth Consumer with my Bitbucket Account with the following details:
Name: jerseytestapp
Description:
CallbackURL: http://localhost:8080/
URL:
Question 1: Could I automate this step?
Step 2: I ran the following Java code:
package jerseytest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
public class BitbucketJersey {
public static void main(String[] args) {
OAuthClientRequest request;
try {
request = OAuthClientRequest
.authorizationLocation("https://bitbucket.org/site/oauth2/authorize")
.setClientId("jerseytestapp")
.setRedirectURI("http://localhost:8080")
.buildQueryMessage();
System.out.println(request.getLocationUri());
} catch (OAuthSystemException e) {
e.printStackTrace();
}
}
}
Step 3: I received the following locationURI and opened in Firefox
https://bitbucket.org/site/oauth2/authorize?redirect_uri=http%3A%2F%2Flocalhost%3A8080&client_id=jerseytestapp
Question 2: Do I need to use the browser or can I do this from the java application?
I receive the following answer message in Firefox:
Invalid client_id
This integration is misconfigured. Contact the vendor for assistance.
Question 3: What would be the correct next steps, and what is wrong with my approach?
Answer 1: You can automate the creation of OAuth Consumers, but you probably don’t want to.
Bitbucket provides documentation on how to create a consumer through their APIs, although the documentation is lacking many pertinent fields. Even so, you could still craft an HTTP request programmatically which mimics whatever Bitbucket's web interface is doing to create consumers. So yes, it could be automated.
Here's why you probably don't want to. In your case, you have three things that need to work together: your application, the end user, and Bitbucket. (Or in terms of OAuth jargon for this flow, those would be the client, resource owner, and authorization server, respectively.) The normal way of doing things is that your application is uniquely identified by the OAuth Consumer that you’ve created in your account, and all usages of Bitbucket by your application will use that single OAuth Consumer to identify your application. So unless you’re doing something like developing a Bitbucket application that generates other Bitbucket applications, you have no need to automate the creation of other OAuth Consumers.
Answer 2: You can authorize directly from your Java application.
Bitbucket states that it supports all four grant flows/types defined in RFC-6749. Your code is currently trying to use the Authorization Code Grant type. Using this grant type WILL force you to use a browser. But that’s not the only problem with this grant type for a desktop application. Without a public webserver to point at, you will have to use localhost in your callback URL, as you are already doing. That is a big security hole because malicious software could intercept traffic to your callback URL to gain access to tokens that the end user is granting to your application only. (See the comments on this stackoverflow question for more discussion on that topic.) Instead, you should be using the Resource Owner Password Credentials Grant type which will allow you to authenticate a Bitbucket’s username and password directly in your application, without the need of an external browser or a callback URL. Bitbucket provides a sample curl command on how to use that grant type here.
Answer 3: The correct next steps would be to model your code after the following sample. What is wrong with your approach is that you are trying to use a grant type that is ill-suited to your needs, and you are attempting to use your OAuth Consumer's name to identify your application instead of your Consumer's key and secret.
The following code sample successfully retrieved an access token with my own username/password/key/secret combination, whose values have been substituted out. Code was tested using JDK 1.8.0_45 and org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.0.
OAuthClientRequest request = OAuthClientRequest
.tokenLocation("https://bitbucket.org/site/oauth2/access_token")
.setGrantType(GrantType.PASSWORD)
.setUsername("someUsernameEnteredByEndUser")
.setPassword("somePasswordEnteredByEndUser")
.buildBodyMessage();
String key = "yourConsumerKey";
String secret = "yourConsumerSecret";
byte[] unencodedConsumerAuth = (key + ":" + secret).getBytes(StandardCharsets.UTF_8);
byte[] encodedConsumerAuth = Base64.getEncoder().encode(unencodedConsumerAuth);
request.setHeader("Authorization", "Basic " + new String(encodedConsumerAuth, StandardCharsets.UTF_8));
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthResourceResponse response = oAuthClient.resource(request, OAuth.HttpMethod.POST, OAuthResourceResponse.class);
System.out.println("response body: " + response.getBody());
Your main problem was that you were giving the customer name instead of the client id:
.setClientId("jerseytestapp")
The only way to get the client id that I know of is to query:
https://bitbucket.org/api/1.0/users/your_account_name/consumers
However, even then it was still not working so I contacted bitbucket support. It turned out that the documentation is misleading. You actually need to use the client key instead.
.setClientId("ydrqABCD123QWER4567") // or whatever your case might be
https://bitbucket.org/site/oauth2/authorize?client_id=client_key&response_type=token

Categories

Resources