How I get menu click event - java

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;
}

Related

How to disable Enable connection to IoT Hub?

I am rehistering succesfully a device in a Azure IoT hub via device provisioning service, but i want to disable the property
Enable connection to IoT Hub
to disable for every registered device.
Is there any way to do this from the code.
You can use the REST API that allows to create or update enrollments (either group enrollments or single enrollments), in particular the provisioningStatus flag. (there is a similar API for individual enrollments).
Next time your device tries to use DPS to get its provisioning info, it will be denied access. If you're caching the IoT Hub credentials, you will need to use the IoT Hub REST API to disable the device (see status flag) that DPS provisioned in the registry.
Yes, there are plenty of libraries available in different different languages.
I am using RegistryManager class of C#. Here's a link!.
Let me share C# code which I am using for same,
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Azure.Devices;
public static class EnableDevice
{
static RegistryManager registryManager;
static string iotHubConnectionString = Environment.GetEnvironmentVariable("iotHubConnectionString");
[FunctionName("EnableDevice")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
ILogger log)
{
JObject response = new JObject();
try
{
string deviceId = req.Query["device_id"];
if (string.IsNullOrEmpty(deviceId))
{
response.Add("message", "Please provide valid device_id in request params or in the request body");
response.Add("code", 400);
return new BadRequestObjectResult(response);
}
registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString);
Device device = await registryManager.GetDeviceAsync(deviceId);
if (device == null)
{
response.Add("message", $"Error while enabling device: Device with {deviceId} not found.");
response.Add("code", 400);
return new BadRequestObjectResult(response);
}
device.Status = DeviceStatus.Enabled; // DeviceStatus.Disabled to Disable device
await registryManager.UpdateDeviceAsync(device);
response.Add("message", "Device enabled successfully");
response.Add("code", 200);
return new OkObjectResult(response);
}
catch (Exception e)
{
response.Add("message", e.Message);
response.Add("stacktrace", e.StackTrace);
response.Add("code", 500);
return new BadRequestObjectResult(response);
}
}
}

JDA - Event if new user joined to Guild

I have a problem, I am trying to code a bot using Java Discord API (JDA).
When a new user joins a server, the bot shall send a message, but my code is not working.
Code:
public class UserJoinModule extends ListenerAdapter {
public void onGuildMemberJoined(GuildMemberJoinEvent event) throws LoginException {
String user = event.getMember().getAsMention();
JDA client = new JDABuilder("awesome token").build();
final List<TextChannel> channels = client.getTextChannelsByName("awesome channel name", true);
for (final TextChannel ch : channels) {
ch.sendMessage("New member joined: " + user).queue();
}
}
}
Can someone tell me what is wrong?
For me the issue was not from the listener and method I override.
I believe you have to add GatewayIntent.GUILD_MEMBERS to your JDABuilder.
builder.enableIntents(GatewayIntent.GUILD_MEMBERS);
This fixed the same issue for me.
In your Main.java or whatever the file is, there is a variable of type JDABuilder, on it's same line of code, there is your token, a .build() at the end etc...
Insert this code into that line:
.enableIntents(GatewayIntent.GUILD_MEMBERS)
So it looks like this:
jda = JDABuilder.createDefault("TOKEN").enableIntents(GatewayIntent.GUILD_MEMBERS).build();
For it to work, go to your Discord Developer Portal, click your bot, from the menu on the left, click Bot, then scroll down and enable:
Server Members Intent
There are still noticeable errors like registering a new client on every message and other issues, fix them, then start your bot and it shall work.
Your code should look like this:
public class UserJoinModule extends ListenerAdapter {
#Override // USE THIS WHEN YOU WANT TO OVERRIDE A METHOD
public void onGuildMemberJoin(GuildMemberJoinEvent event) {
String user = event.getMember().getAsMention();
JDA client = event.getJDA(); // DO NOT CREATE A NEW JDA INSTANCE EVERY TIME
List<TextChannel> channels = client.getTextChannelsByName("awesome channel name", true);
for (TextChannel ch : channels) {
ch.sendMessage("New member joined: " + user).queue();
}
}
}
And you must register this listeners in your JDABuilder instance, preferably you only have one of these in your entire codebase. See addEventListeners.
You have 2 problems in your code.
You are creating a new JDA client every time a member joins.
You are sending messages to every channel with that name, in every guild. Not just the guild that the user joined.
Here is what you want to do:
public class UserJoinModule extends ListenerAdapter {
#Override
public void onGuildMemberJoin(GuildMemberJoinEvent event) {
Guild guild = event.getGuild(); // Get the guild that the user joined.
User user = event.getUser(); // Get the user that joined.
JDA client = event.getJDA(); // Get the already existing JDA instance.
List<TextChannel> channels = guild.getTextChannelsByName("awesome channel name", true); // Get the list of channels in the guild that matches that name.
for (TextChannel channel : channels) { // Loops through the channels and sends a message to each one.
channel.sendMessage("New member joined: " + user).queue();
}
}
}

Hide push notification if it contains specific elements

I won't show a received push notification from appearing top notifications menu my notification if it has for example key update. For now if I get notification with this key, all notifications are in the notification bar. I want to not present this notifications for user.
I'm using WakefulBroadcastReceiver for handle notifications like below:
public class PusherReceiver extends WakefulBroadcastReceiver {
private boolean isAppOnForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null)
return false;
final String packageName = context.getPackageName();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}
public void onReceive(final Context context, Intent intent) {
Log.i("SimpleWakefulReceiver", "Starting service # " + SystemClock.elapsedRealtime());
if (!isAppOnForeground((context))) {
String pushNotificationBody = intent.getStringExtra("alert");
try {
JSONObject notificationData = new JSONObject(pushNotificationBody);
// This is the Intent to deliver to our service.
Intent service = new Intent(context, BackgroundService.class);
// Put here your data from the json as extra in in the intent
service.putExtra("notification", pushNotificationBody);
Log.i("PUSH_NOTIFICATION_JSON", "RECEIVED JSON " + notificationData);
// Start the service, keeping the device awake while it is launching.
if (!notificationData.has("update")) {
startWakefulService(context, service);
} else {
// Do nothing
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
UPDATE:
I changed project a little and with Onesignal and his NotificationExtenderService, I did something like below:
public class NotificationNotDisplayingExtender extends NotificationExtenderService {
#Override
protected boolean onNotificationProcessing(OSNotificationReceivedResult receivedResult) {
String notification = receivedResult.toString();
String notificationBody = receivedResult.payload.body;
JSONObject notificationBodyJSON = null;
try {
notificationBodyJSON = new JSONObject(notificationBody);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject pushNotificationData = notificationBodyJSON;
boolean hidden = false;
if (pushNotificationData.has("update")) {
Log.i("NOTIFICATION MANAGER", "PREVENT DISPLAY NOTIFICATION");
hidden = true;
}
// Return true to stop the notification from displaying.
return hidden;
}
}
And it prevent displaying notifications with update key, but now I don't receive it in my PusherReceiver to start my service. Is there easy way to send data from my NotificationNotDisplayingExtender receivedResult to my PusherReceiver?
For now it looks like my PusherReceiver don't fire his onReceive method.
Many thanks for help in advance.
There are two types of payload.
1. Data
2. Notification
https://developers.google.com/cloud-messaging/concept-options
Use only data payload. Then you always get the call in FirebaseMessagingService onMessageRececived Method
The thing is basically we have two type of notifications.
One which can be called Notification Type, is that the push has a notification object in sent/received bundle, in which you have to handle it when your app is in foreground and the notification is received. In this case, if your app is in foreground, then you can handle it and do whatever you like which is not showing a notification. But if the app is in background, a notification will automatically create by google and it takes predefined title and message objects within the received push bundle to make the notification.
Second type which can be called Data Type, do not have any notification object in the sent/received bundle. In this scenario, your app is in foreground or background, you should handle everything. So, if you put your data in data object of your push notification message, everything will be in your hands.
So, in short, just put your data in data object of your notification and implement your desired logic.
I do not see the JSON data you are referring to. However, I suppose the update key in your JSON is containing null. In your code you are checking if the JSON data has the key update in it. This function will always return true if the key exists in the JSON body. You might have the field with null value which is indicating that you are not supposed to show the notification in the system tray.
In that case, you might consider using isNull function. It returns true if this object has no mapping for update or if it has a mapping whose value is null.
// Start the service, keeping the device awake while it is launching.
if (!notificationData.isNull("update")) {
startWakefulService(context, service);
} else {
// Do nothing
}
And yes, please use the data payload from the notification that you get.
Every time you notify the NotificationManager to show a notification, you provide an ID to be used for the notification to edit or cancel that notification later on. If you show a notification by manager.notify(notificationId, notification), you can cancel it with manager.cancel(notificationId).
If you want to remove all the notifications, you can use NotificationManager.cancelAll().

Get calendar events from Outlook.com using Java API

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.

SNS aws not working properly

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.

Categories

Resources