Read email from office365 inbox without using of IMAP and POP3 - java

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.

Related

Unclear how to connect Plivo to OpenTok Java SDK SIP

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.

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.

CXF + wsdl2java + authentication

I created the jar from the WSDL for my client using the wsdl2java command. Now, I need to know how I can authenticate my client in order to complete an operation?
I am using CXF 2.7.16. I created my service using the generated class MyApp_Service, I am struggling with this. Isn't there a simple way to tell my client the credentials it should use to gain access to the web service?
I read about the Spring configuration, however I am unable to figure out if it applies to my case and how if yes. I tried to cast the MyApp_Service class to BindingProvider in order to use the method which consist to put the USERNAME and PASSWORD properties in the context with a value. However, MyApp_Service cannot be cast to BindingProvider.
This is my first web service client application ever. So, any help will be welcomed.
Update 2015-05-28: I tried to define the AuthenticationPolicy but is seems not working. Here is the code:
Client client = JaxWsDynamicClientFactory.newInstance().createClient(wsdlUrl);
ClientImpl clt = (ClientImpl) client;
HTTPConduit cc = (HTTPConduit) clt.getConduit();
org.apache.cxf.configuration.security.ObjectFactory secOF = new org.apache.cxf.configuration.security.ObjectFactory();
AuthorizationPolicy ap = secOF.createAuthorizationPolicy();
ap.setUserName(usagerWS);
ap.setPassword(mdpWS);
ap.setAuthorizationType("Basic");
cc.setAuthorization(ap);
Sniffing with WireShark, the Authorization header is clearly missing in the HTTP request.
What is missing?
Problem solved, here is the solution:
MyApp_Service service = new MyApp_Service(wsdlUrl, new QName(namespace, serviceName));
MyApp port = service.getMyApp();
// Set credentials
Map<String, Object> reqCtxt = ((javax.xml.ws.BindingProvider) port).getRequestContext();
reqCtxt.put(javax.xml.ws.BindingProvider.USERNAME_PROPERTY, username);
reqCtxt.put(javax.xml.ws.BindingProvider.PASSWORD_PROPERTY, password);
No more usage of the dynamic client. Only the classes generated with wsdl2java are used.

Google Drive API - OAuth2.0: How to Automate Authentication Process? Doubts and Questions

I'm trying to integrate Google APIs inside a project (Thesis project) and I have some doubts and questions. So, here it is the scenario:
I wrote a back-end application in Java that runs solely from a command-line and has absolutely no interaction with a user. Its goal is to allow communication and interaction between sensors and actuators. Everything works great. Now I'd like to integrate something in order to let the sensors backup data both with a certain periodicity and due to some detected threshold value. So I thought, why not trying with Google Drive. The first very useful links have been:
https://developers.google.com/drive/web/quickstart/quickstart-java
https://developers.google.com/accounts/docs/OAuth2InstalledApp
Quick start examples work like a charm. However it requires quite a bit of settings: create a project inside the Developer Console (therefore an account), enable Drive API, then create a Client ID and a Client Secret. Once you've done these steps, you can hard-coded client ID and secret to form the request URL for google drive. Then you're kindly asked to enter the url in a browser, log in if you're not, accept and finally copy and paste into your console the authorization code for obtaining an access token. Wow, quite a security proccess. But hey, I completely agree with it, above all in a scenario where we have either a web app, a smartphone app or a web service that needs users' authentication and authorization in order to let the app doing its job by accessing someone else account. But in my case, I just would like that sensors will backup data on my google drive.
These facts lead to my first question: in order to use Google APIs (Drive in this case), do I have to create a project anyway? Or is there another approach? If I'm not wrong, there aren't other ways to create a client Id and secret without creating a project inside the Developer Console. This puzzles me a lot. Why should I create a project to use basically some libraries?
So, let's assume the previous as justifiable constraints and move on the real question: how to automate the authentication process? Given my scenario where a sensor (simply a Java module) want to backup data, it would be impossible to complete all that steps. The google page about OAuth 2.0 has a great explanations about different scenarios where we can embed the authentication procedure, included one for "devices with limited input capabilities". Unluckily, this is more complicated then the others and requires that "The user switches to a device or computer with richer input capabilities, launches a browser, navigates to the URL specified on the limited-input device, logs in, and enters the code." (LOL)
So, I didn't give up and I ended up on this post that talks about OAuth Playground: How do I authorise an app (web or installed) without user intervention? (canonical ?). It really looks like as a solution for me, in particular when it says:
NB2. This technique works well if you want a web app which access
your own (and only your own) Drive account, without bothering to write
the authorization code which would only ever be run once. Just skip
step 1, and replace "my.drive.app" with your own email address in step
5.
However if I'm not wrong, I think that OAuth Playground it's just for helping test and debug projects that use Google APIs, isn't it? Moreover, Google drive classes such as GoogleAuthorizationCodeFlow and GoogleCredential (used inside the Java quick start example) always need Client ID, Client Secret and so on, which brings me to point zero (create a project and do the whole graphical procedure).
In conclusion: is there a way to avoid the "graphical" authentication interaction and convert it into an automated process using only Drive's APIs without the user intervention? Thanks a lot, I would be grateful for any tip, hint, answer, pointer :-)
This is just a snippet of code that I wrote thanks to pinoyyid suggestions. Just to recap what we should do in this case (when in your program there isn't a user interaction for completing all the Google GUI authentication process). As reported in https://developers.google.com/drive/web/quickstart/quickstart-java
Go to the Google Developers Console.
Select a project, or create a new one.
In the sidebar on the left, expand APIs & auth. Next, click APIs. In the list of APIs, make sure the status is ON for the Drive API.
In the sidebar on the left, select Credentials.
In either case, you end up on the Credentials page and can create your project's credentials from here.
From the Credentials page, click Create new Client ID under the OAuth heading to create your OAuth 2.0 credentials. Your application's client ID, email address, client secret, redirect URIs, and JavaScript origins are in the Client ID for web application section.
The pinoyyd post is neater and get straight to the point: How do I authorise a background web app without user intervention? (canonical ?)
Pay attention to step number 7
Finally the snippet of code is very simple, it's just about sending a POST request and it's possible to do that in many ways in Java. Therefore this is just an example and I'm sure there is room for improvements ;-)
// Both to set access token the first time that we run the module and in general to refresh the token
public void sendPOST(){
try {
URL url = new URL("https://www.googleapis.com/oauth2/v3/token");
Map<String,Object> params = new LinkedHashMap<>();
params.put("client_id", CLIENT_ID);
params.put("client_secret", CLIENT_SECRET);
params.put("refresh_token", REFRESH_TOKEN);
params.put("grant_type", "refresh_token");
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
BufferedReader in_rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
// Read response body which should be a json structure
String inputLine;
StringBuilder responseBody = new StringBuilder();
while ((inputLine = in_rd.readLine()) != null) {
responseBody.append(inputLine);
}
in_rd.close();
//Parsing Response --> create a json object
JSONObject jsonResp = new JSONObject(responseBody);
//Modify previous access token String
ACCESS_TOKEN = jsonResp.getString("access_token");
}
catch(MalformedURLException ex_URL){
System.out.println("An error occured: " + ex_URL.getMessage());
}
catch(JSONException ex_json) {
System.out.println("An error occured: " + ex_json.getMessage());
}
catch(IOException ex_IO){
System.out.println("An error occured: " + ex_IO.getMessage());
}
} //end of sendRefreshPOST method
Hope this snippet of code will help others that will face the same situation !
I wrote the SO post at How do I authorise an app (web or installed) without user intervention? (canonical ?)
What it describes is indeed the solution to your use-case. The key bit you'd missed is step 7 where you enter the details of your own application into the OAuth Playground. From that point, the playground is impersonating your app and so you can do the one-time authorization and obtaining a refresh token.

how to make authentication using version one api

I want to export data from VersionOne into my own Java application. Please help me retrieve this data from it. I used the following code but it is not working.
V1APIConnector dataConnector = new V1APIConnector("http://www10.v1host.com/loxvo/rest-1.v1/", "username", "password");
V1APIConnector metaConnector = new V1APIConnector("http://www10.v1host.com/loxvo/meta.v1/");
metaModel = new MetaModel(metaConnector);
services = new Services(metaModel, dataConnector);
It seems there is some problem from with my URL. Please tell me what will be proper URL here as my company URL is https://www10.v1host.com/loxvo/
You have the correct form of the URL in your post, but not in your sample code. All hosted instances use https as you have shown at the end, but your code has http. While a browser will simply accept a redirect and take you from http to https, the API Client code does not; it simply fails to establish a connection.

Categories

Resources