I want to get all calendar events from Outlook.com using Java API. I tested this code to connect:
public void findChildFolders(String username, String password) throws Exception
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
ExchangeCredentials credentials = new WebCredentials(username, password);
// URI jira_url = URI.create("outlook.live.com");
service.autodiscoverUrl(username, new RedirectionUrlCallback());
service.setCredentials(credentials);
FindFoldersResults findResults = service.findFolders(WellKnownFolderName.Inbox, new FolderView(Integer.MAX_VALUE));
for (Folder folder : findResults.getFolders())
{
System.out.println("Count======" + folder.getChildFolderCount());
System.out.println("Name=======" + folder.getDisplayName());
}
}
static class RedirectionUrlCallback implements IAutodiscoverRedirectionUrl
{
#Override
public boolean autodiscoverRedirectionUrlValidationCallback(
String redirectionUrl)
{
return redirectionUrl.toLowerCase().startsWith("https://");
}
}
But I get error stack:
microsoft.exchange.webservices.data.autodiscover.exception.AutodiscoverLocalException: The Autodiscover service couldn't be located.
at microsoft.exchange.webservices.data.autodiscover.AutodiscoverService.internalGetLegacyUserSettings(AutodiscoverService.java:742)
What is the proper way to implement this code?
A full working example of obtaining a room resource calendar is here: Office365 API - Admin accessing another users/room's calendar events. You can easily adapt the code to obtain the calendar events from the same user that was authenticated, or another user/email/resource if your authenticated user has rights to it.
Related
This question already has answers here:
How to exclude an element from a Firestore query?
(8 answers)
Closed 1 year ago.
I am trying to retrieve UID of all the users except of the current user. I tried to do FirebaseAuth.getInstance().getUid(); but it returns CurrentUserUid. Is there a way for NOT getting UID of the current user?
When you are using your app, you are considered as a normal user and not an admin or privileged user. Client SDKs cannot fetch information about other users. You would have to use a secure environment such as Cloud Functions or your own along with Admin SDK to retrieve information about other users.
You can create a Callable Function that fetched a specific user by email or UID like this:
export const getUser = functions.https.onCall(async (data, context) => {
// Verify if the user requesting data is authorized
const {email} = data;
const userRecord = await admin.auth().getUserByEmail(email)
return userRecord.uid
});
You can then call this function from your Android app like this:
private Task<String> getUserInfo(String userEmail) {
// Create the arguments to the callable function.
Map<String, Object> data = new HashMap<>();
data.put("email", userEmail);
return mFunctions
.getHttpsCallable("getUser")
.call(data)
.continueWith(new Continuation<HttpsCallableResult, String>() {
#Override
public String then(#NonNull Task<HttpsCallableResult> task) throws Exception {
// This continuation runs on either success or failure, but if the task
// has failed then getResult() will throw an Exception which will be
// propagated down.
String result = (String) task.getResult().getData();
return result;
}
});
}
Do note that you must check if the user calling the function and requesting the data is authorized. You can check custom claims, the UID or any identifier that decides who can view others users' information.
If your application requires anyone to view all information, then you would have to use any database that stores users' information and can be fetched on your app because you cannot fetch that data using Client Auth SDK.
I'm using Twitter4j's TwitterStream functionality to receive a stream of a heavily followed Twitter user's tweets, as follows:
...
private void initTwitterStream(AccessToken accessToken) {
twitterStream = new TwitterStreamFactory().getInstance();
twitterStream.setOAuthConsumer(consumerKey, consumerSecret);
twitterStream.setOAuthAccessToken(accessToken);
twitterStream.addListener(createUserStreamListener());
twitterStream.user("realDonaldTrump");
logger.info("Listener initiated; listening for status updates.");
}
private UserStreamListener createUserStreamListener() {
return new UserStreamAdapter() {
public void onStatus(Status status) {
log(status); // logs the tweet author and text
}
};
}
...
The problem I have is that I'm getting updates from anyone who has tagged this user in their tweet. For example:
16:22:02.150 [Twitter4J Async Dispatcher[0]] INFO c.d.i.twitter.TwitterListenerService - Received status update from [foo1234]: #realDonaldTrump never trust a man's perspective of technology after he uses "cyber" as a noun
How do I configure Twitter4j so that I only receive tweets authored by this user, and not tweets that mention him?
My overall goal is to be able to automatically download a daily report using the bing ads API. To do this, I need to authenticate with OAuth (the old PasswordAuthentication method doesn't work because I have a new microsoft account). I have been through the "Authorization Code Grant Flow" manually and authorised myself successfully. The problem is:
the token is only valid for 1 hour
when the token expires, the process requires the user to manually login using a web browser again and re-allow the app access
Here's an example desktop app using OAuth
Does somebody know either
a more fitting way of authenticating?
or a way of bypassing the user interaction?
SOLUTION:
As mentioned by #eric urban it is only necessary to authorize manually, once. after that, the refresh token will do. (Not really obvious just looking at the example desktop app!)
I wrote a class to deal with all the OAuth stuff and persist the refresh token to a file
public class OAuthRefreshToken {
private static String refreshTokenFileName = "./bingAdsRefreshToken.txt";
private static String ClientId = "XXXXX";
private final OAuthDesktopMobileAuthCodeGrant oAuthDesktopMobileAuthCodeGrant = new OAuthDesktopMobileAuthCodeGrant(ClientId);
private String refreshToken;
public OAuthRefreshToken() {
oAuthDesktopMobileAuthCodeGrant.setNewTokensListener(new NewOAuthTokensReceivedListener() {
#Override
public void onNewOAuthTokensReceived(OAuthTokens newTokens) {
String refreshTime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(new java.util.Date());
refreshToken = newTokens.getRefreshToken();
System.out.printf("Token refresh time: %s\n", refreshTime);
writeRefreshTokenToFile();
}
});
getRefreshTokenFromFile();
refreshAccessToken();
}
public OAuthRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
writeRefreshTokenToFile();
}
public OAuthDesktopMobileAuthCodeGrant getoAuthDesktopMobileAuthCodeGrant() {
return oAuthDesktopMobileAuthCodeGrant;
}
private void refreshAccessToken(){
oAuthDesktopMobileAuthCodeGrant.requestAccessAndRefreshTokens(refreshToken);
}
private void getRefreshTokenFromFile(){
try {
refreshToken = readFile(refreshTokenFileName, Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
}
}
private static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
private void writeRefreshTokenToFile(){
File refreshTokenFile = new File(refreshTokenFileName);
try {
FileWriter f2 = new FileWriter(refreshTokenFile);
f2.write(refreshToken);
f2.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
System.out.printf("New refresh token: %s\n", refreshToken);
System.out.printf("Stored Safely in: %s\n", refreshTokenFileName);
}
}
Use it in your app like:
final OAuthRefreshToken oAuthRefreshToken = new OAuthRefreshToken();
final OAuthDesktopMobileAuthCodeGrant oAuthDesktopMobileAuthCodeGrant = oAuthRefreshToken.getoAuthDesktopMobileAuthCodeGrant();
You are correct that user consent is required up front (once). Thereafter you can use the refresh token to request additional access tokens without user interaction. For details about Authorization Code grant flow using the Bing Ads Java SDK please see Getting Started Using Java with Bing Ads Services. Does this help?
The refresh token should not expire that quickly, they are usually permanent or last a very long time. These can however be revoked, or invalidated if you request too many of them. i believe when you have requested more than 25 different refresh tokens, they older ones start to become invalid.
Hello all i wrote an application grabbing photos from facebook. I did that successfully. Now i wrote a notification service using SNS in java. Basically sending out subscription for first time users who log into my application and also when a pictured has been deleted from the repository. My first problem is when i download the pics and user info from facebook, i want to check if its a new user or not. If a new user send out a subscription and if not(basically user exist in mongoDb dont send out email for subscription) but my code keeps sending out email to everyuser. And lastly when a user deletes a photo they get a notification but when i tested it i failed to get an email. Below is my code could someone tell me what im doing wrong.
public class EmailNotifications {
private static final String accessKey = "****************";
private static final String secretAccess ="***********************";
//Notification when user gets info from facebook app for first time.
public static void SignUP(String email, String Topic){
AmazonSNSClient snsClient = new AmazonSNSClient(new BasicAWSCredentials(accessKey, secretAccess));
snsClient.setRegion(Region.getRegion(Regions.US_WEST_1));
//create a Topic
CreateTopicRequest createTopicRequest = new CreateTopicRequest().withName(Topic);
CreateTopicResult createTopicResult = snsClient.createTopic(createTopicRequest);
//subscribes to a topic
SubscribeRequest subscribeRequest = new SubscribeRequest().withTopicArn(createTopicResult.getTopicArn())
.withProtocol("email").withEndpoint(email);
snsClient.subscribe(subscribeRequest);
}
//Notification when photo is deleted
public static void deletePic(String email, String topic, String message){
AmazonSNSClient snsClient = new AmazonSNSClient(new BasicAWSCredentials(accessKey,secretAccess));
snsClient.setRegion(Region.getRegion(Regions.US_WEST_1));
CreateTopicRequest create = new CreateTopicRequest(topic);
CreateTopicResult result = snsClient.createTopic(create);
System.out.println(result);
//String msg = "My text published to SNS topic with email endpoint";
PublishRequest publishRequest = new PublishRequest(result.getTopicArn(), message);
publishRequest.setSubject("Deleted Pic");
/*PublishResult pu= */snsClient.publish(publishRequest);
}
}
Below is my implementation of both delete and grabbing data for first assuming mongodb is empty:
Delete photo implementation:
#Override
//deletes photo from mongoDB... but doesn't send out an email stating phootid
public String deletePhoto(String id, String PhotoId){
String mssg="";
if(accountRepo.exists(id)){
UserAccounts userAccounts=accountRepo.findById(id);
UserPhotos photos = photoRepo.findByPhotoId(PhotoId);
mssg="The picture "+photos.getPhotoId()+" has been deleted from the application";
EmailNotifications.deletePic(userAccounts.getEmail(),topic,mssg);
photoRepo.delete(PhotoId);
return "Photo is deleted";
}
else
return "Photo does not exist";
}
Grabbing photo from face for the first time. The user should get only one notification max. But i keep getting several messages.
#Override
public UserAccounts create(FacebookClient facebookClient){
User me = facebookClient.fetchObject("me", User.class);
UserAccounts userAccounts = new UserAccounts();
userAccounts.setEmail(me.getEmail());
userAccounts.setGender(me.getGender());
userAccounts.setId(me.getId());
userAccounts.setName(me.getName());
accountRepo.save(userAccounts);
EmailNotifications.SignUP(me.getEmail(), topic);
return userAccounts;
}
Could some one assist me on this
Judging by your description and the code, it would guess the email you keep getting when you download for a user is the subscription confirmation email because all EmailNotifications.SignUp does is subscribe the email address.
I would guess that the reason you haven't getting any email when you delete a picture is because you haven't confirmed the subscription. In the subscription confirmation emails, there should be a link you can click on to confirm the subscription.
As for why you keep getting the email every time you download, I can't tell from your code, but in the create method you show there is not if block around calling SignUp to check if the user already existed, which I imagine is your problem.
As an aside, if your application is interacting with users and you want a good email experience, you would probably be better off using SES, which allows you to completely control the formatting and branding of your email.
I created a custom menu using mirror api.
menu created method on MainServlet
public List<MenuItem> makeDealMenu(String appBaseUrl) {
String dealMenuIconUrl = appBaseUrl + "static/images/deal_50.png";
MenuValue dealMenuValue = new MenuValue();
dealMenuValue.setDisplayName("DEAL");
dealMenuValue.setIconUrl(dealMenuIconUrl);
List<MenuValue> dealMenuValueList = new ArrayList<MenuValue>();
dealMenuValueList.add(dealMenuValue);
MenuItem dealMenuItem = new MenuItem();
dealMenuItem.setAction("CUSTOM");
dealMenuItem.setId("dealMenu");
dealMenuItem.setValues(dealMenuValueList);
List<MenuItem> customMenuItemList = new ArrayList<MenuItem>();
customMenuItemList.add(dealMenuItem);
return customMenuItemList;
}
From doPost method I call MirrorClient
MirrorClient.insertSubscription(credential,
WebUtil.buildUrl(request, "/notify"), userId, "timeline");
In MirrorClient define method insertSubscription
public static Subscription insertSubscription(Credential credential,
String callbackUrl, String userId, String collection)
throws IOException {
LOG.info("Attempting to subscribe verify_token " + userId
+ " with callback " + callbackUrl);
callbackUrl = callbackUrl.replace("appspot.com", "Appspot.com");
Subscription subscription = new Subscription();
subscription.setCollection(collection);
subscription.setCallbackUrl(callbackUrl);
subscription.setUserToken(userId);
return getMirror(credential).subscriptions().insert(subscription)
.execute();
}
then in NotifyServlet receive the event this way..
JsonFactory jsonFactory = new JacksonFactory();
Notification notification = jsonFactory.fromString(notificationString,
Notification.class);
if (notification.getUserActions().contains(
new UserAction().setType("CUSTOM"))) {
String selectedCustomMenuItemId = notification.getItemId();
if ("dealMenu".equals(selectedCustomMenuItemId)) {
LOG.info("********** I am here in event");
}
}
In Google Cloud Console I set callback url
http://localhost:8080/oauth2callback
https://mirrornotifications.appspot.com/forward?url=http://localhost:8080/notify
http://localhost:8080
How can I get menu's click event or action from my Servlet? Please somebody help....
From mirror api java sample app you can see NotifyServlet implementation. (Or what type server you have find the relevant sample project from quickstart samples).
Firstly you have to define your notification callback to the mirror api. Then you must subscribe register for notifications. After this all menu selections for your glassware are going to be passed to your notification callback(servlet for notifications) througt mirror api.
If your servlet is written on Java try this at your notification callBack:
JsonFactory jsonFactory = new JacksonFactory();
// notificationString is parsed form httpRequest's inputstream which is send from Mirror API
Notification notification = jsonFactory.fromString(notificationString, Notification.class);
if (notification.getUserActions().contains(new UserAction().setType("CUSTOM").setPayload("dealMenu")) {
// User selected CUSTOM menu item on your glassware
}
Edit: Define your notification callback url https. from this:
http://localhost:8080/notify
To this:
https://mirrornotifications.appspot.com/forward?url=http://localhost:8080/notify
To subscribe to notifications in a production environment, you must
provide a callback URL with a valid SSL certificate to handle the
notification. For development purposes, you can use a subscription
proxy server provided by Google that forwards notifications to a
non-SSL callback URL.
https://developers.google.com/glass/tools-downloads/subscription-proxy
Edit2 I modified sample java project a little bit to make it work for notifications on localhost. You may want to put below code to MirrorClient class's insertSubscription method:
// To work with notifications, modify the notify callback's url by adding subscription-proxy
// callbackUrl = "https://mirrornotifications.appspot.com/forward?url=" + callbackUrl;
if("http://localhost:8080/notify".equals(callbackUrl)) {
callbackUrl = "https://mirrornotifications.appspot.com/forward?url=" + callbackUrl;
}