How can i add extra key in UrbanAirship API using java - java

I am sending push notifications using UrbanAirship API using java.
Here is the doc: http://docs.urbanairship.com/api/
I want to send a push notifications with custom key/value. For example, I want send to following to Android/iOS device
name: "Jack"
String appKey = "appKey";
String appSecret = "appSecret";
// Setup an authenticated APIClient with your application key and
// application master secret.
APIClient apiClient = APIClient.newBuilder()
.setKey(appKey)
.setSecret(appSecret)
.build();
// Setup a push payload to send to the API with our handy builders
PushPayload payload = PushPayload.newBuilder()
.setAudience(Selectors.all())
.setNotification(Notifications.notification("UA Push"))
.setDeviceTypes(DeviceTypeData.of(DeviceType.IOS))
.build();
// Try and send, handle anything that comes up
try {
APIClientResponse<APIPushResponse> response = apiClient.push(payload);
logger.info("Sent a push message!");
}
// Non 200 responses throw an APIRequestException. Check the documentation
// to debug your request.
catch (APIRequestException ex){
logger.error("Non 200 request, checking error details and taking action");
}
// An underlying error occurred, most likely outside of the scope of the
// UA library, do some HTTP debugging
catch (IOException e){
logger.error("Broken pipe what?");
}
Here is the code reference for android - https://github.com/urbanairship/java-library/blob/master/src/test/java/com/urbanairship/api/push/model/notification/android/AndroidDevicePayloadTest.java
How can i do send push notification with custom key/value using AndroidDevicePayload ?

You can create your notification like this:
public PushPayload createPushPayloadCustom(String namedUser, String message) {
Notification notification = Notification.newBuilder()
.addDeviceTypeOverride(DeviceType.IOS, IOSDevicePayload.newBuilder()
.setAlert(message)
.build())
.addDeviceTypeOverride(DeviceType.ANDROID, AndroidDevicePayload.newBuilder()
.setAlert(message)
.build())
.build();
return PushPayload.newBuilder()
.setAudience(Selectors.namedUser(namedUser))
.setNotification(notification)
.setDeviceTypes(DeviceTypeData.of(DeviceType.ANDROID, DeviceType.IOS))
.build();
}

You can add to the "extras" object any key/value:
DeviceTypeData deviceTypeData = DeviceTypeData.of(DeviceType.IOS, DeviceType.ANDROID);
IOSDevicePayload iosPayload = IOSDevicePayload.newBuilder()
.setAlert(message)
.addExtraEntry("custom_ios_key", "custom value for IOS")
.build();
AndroidDevicePayload androidPayload = AndroidDevicePayload.newBuilder()
.setAlert(message)
.addExtraEntry("custom_android_key", "custom value for Android")
.build();
PushPayload payload = PushPayload.newBuilder()
.setAudience(Selectors.namedUser(email))
.setNotification(Notifications.notification(iosPayload,androidPayload))
.setDeviceTypes(deviceTypeData)
.build();
Then in the received push, you will find the object:
For more details go to urbanairship official documentation

Related

Azure Functions Java using ServiceBusQueueOutput to send message with schedule enqueue time

message send to the servicebus can be processed by consumer after some time, simply by setting ScheduledEnqueueTime param.
Its easy to achieve this while working on "raw" service bus message ie:
var serviceBusMessage = new ServiceBusMessage(json);
serviceBusMessage.setScheduledEnqueueTime(someTime);
but I have azure functions java app, that has:
#FunctionName("Process-Notifications")
public void processNotifications(
#ServiceBusQueueTrigger(name = "MessageCmd", queueName = "queue_name_notify_cmd_v1", connection = "SBusConn") String messageCmd,
#ServiceBusQueueOutput(name = "NotifyForRetry", queueName = "queue_name_notify_cmd__v1", connection = "SBusConn") OutputBinding<String> notifyForRetry,
sending notification is easy here, I only do:
Map<String, Object> result = mapper.convertValue(json, new TypeReference<>() {
});
String channels = "";
if (error instanceof SmsOnlyError) {
channels+="sms";
}
if (error instanceof EmailOnlyError) {
channels+="email";
}
if (error instanceof AllDefinedChannelsError) {
channels+="sms, email";
}
properties.put("retry_channels", channels);
result.put("UserProperties", properties);
result.put("ScheduledEnqueueTime", OffsetDateTime.now(defaultClock).plusMinutes(15).toString());
JsonNode newJson = mapper.convertValue(result, JsonNode.class);
hard to find something in docs, maybe someone here can me ?
thanks!
and works fine. But I have no idea how to set ScheduledEnqueueTime there..
Unfortunately, this isn't currently supported by non-C# languages in Azure Functions. You would have to use the Azure SDK for Service Bus directly in your code.

Get Member details using Java in Microsoft Bot Framework SDK

I am currently working on delivering 1:1 messages to the users in Teams.
Problem Statement: I am having trouble trying to get the member details to populate the Channel Account to set the ConverstationParameters object to create conversation if the user is not part of a team. Is there a way I could get the details of the user without having the user part of a Team. I wasn't able to find any reference documentation to how to get this information for Java.
Below is my code snippet:
Setup credentials and initialize a connection using Connector Client.
Populate Channel account with recipient details for set members on Conversation Parameters Object.
Activity message = MessageFactory.text("Hello World");
MicrosoftAppCredentials credentials = new MicrosoftAppCredentials(appClientID, appClientSecret);
try (ConnectorClient client = new RestConnectorClient(serviceUrl, credentials)) {
logger.info("** Connector Client Set: {} **", client);
ConversationParameters conversationParameters = new ConversationParameters();
conversationParameters.setIsGroup(false);
CompletableFuture<ChannelAccount> user = ((Conversations) client.getConversations())
.getConversationMember(recipient, teamsInternalId); // Don't want to use this because the user has to be part of the same team which is not true in our case.
logger.info("** Aysnc get User details call **");
logger.info("** AAID: {} **", user.get().getAadObjectId());
try {
conversationParameters.setMembers(Collections.singletonList(user.get()));
} catch (ErrorResponseException e) {
logger.error("** User Error : {}**", e.getMessage());
}
conversationParameters.setTenantId(tenantId);
TenantInfo tenantInfo = new TenantInfo(tenantId);
TeamsChannelData channelData = new TeamsChannelData();
channelData.setTenant(tenantInfo);
conversationParameters.setChannelData(channelData);
CompletableFuture<ConversationResourceResponse> conversationResourceResponse = new CompletableFuture<ConversationResourceResponse>();
try {
conversationResourceResponse = client.getConversations()
.createConversation(conversationParameters);
logger.info("** Create Conversation: {} **", conversationResourceResponse.get().getId());
} catch (ErrorResponseException e) {
logger.error("** Create Conversation : {} **", e.getMessage());
}
CompletableFuture<ResourceResponse> response = client.getConversations()
.sendToConversation(conversationResourceResponse.get().getId(), message);
logger.info("** Send Conversation **", response.get().getId());
I solved the above requirement following these steps:
Check if my app is installed for the user using Graph API.
If not installed, force install the app for the user using Graph API.
Then retrieve the conversation chat id.
Use this chat id to send the message to the user.
There steps are outline here on the MSFT reference page:
https://learn.microsoft.com/en-us/microsoftteams/platform/graph-api/proactive-bots-and-messages/graph-proactive-bots-and-messages?tabs=dotnet
I hope this answer helps anyone in the same boat who would like to send messages directly 1:1 from an app to a Teams user without any mutual Team condition.

Watch Google Calendar event for changes and updating server-side

I'm trying to listen to a Google Calendar event I created using a watch request but I have no clue how to get the event details once I get the push notification.
So this is what I have so far, I create the Calendar event using JavaScript (it prompts the user for authorization):
function createEvent(data) {
var request = gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': data
});
request.execute(function(event) {
if (!event.code) {
openToast('The event was added to your Google Calendar')
watchEvent(data.id);
}
});
}
And then I create a watch request to get the PUSH notifications:
function watchEvent(eventId) {
gapi.client.calendar.events.watch({
auth: gapi.auth2.getAuthInstance(),
resource: {
id: eventId,
type: 'web_hook',
address: webhookUrl
},
calendarId: 'primary'
}).execute(function onWatchCalendarEvent(event) {
if (event.error) {
console.error('Error creating event watch webhook', event.error);
}
});
}
So far so good, this is working OK and I receive a PUSH notification with the channelID from which I can get my own internal meetingId.
#PostMapping
public void onCalendarEventUpdate(#RequestHeader(name = "x-goog-channel-id") String channelId,
#RequestHeader(name = "x-goog-resource-state") String resourceState) {
log.info("Received Google Calendar event update notification: " + resourceState);
// only when the event is modified google posts the resource state as "exists"
// (what kind of name is that anyway?)
if (resourceState.equals("exists")) {
// get the meeting ID from the channel ID
Long meetingId = findMeetingIdFromChannelId(channelId);
calendarService.updateMeeting(meetingsService.findById(meetingId));
}
}
I've read the docs for Authorizing Requests, PUSH Notifications and Java API Getting Started but they all prompt for the user authorization. Since this PUSH notification is happening asynchronously how am I supposed to get the updated event details? Thanks
if you have the calendar and event id (e.g. from the notification you get from Google that you receive and parse at your webhookUrl location), you can make calendar api calls to get all the event details: https://developers.google.com/calendar/api/v3/reference/events/get

Telegram API methods - 404 error | java

Created a bot and group. Added bot to the group(as admin) and starting trying posts. Through Url, it's smooth and successful. Started off exploring Telegram API(JAVA). Tests were on getUpdate and sendMessage methods.
I have generated TOKEN from telegram webapp(https://web.telegram.org).
Code snippet to getUpdates: yes, I have included bot ahead of the token.
TelegramBot bot = new TelegramBot("BOT_TOKEN");
GetUpdates getUpdates = new GetUpdates().limit(100).offset(0).timeout(0);
GetUpdatesResponse gur = bot.execute(getUpdates);
List<Update> list = gur.updates();
for(Update update : list) {
System.out.println(update.message());
}
Resonse is null.
code for sendMessage:
SendMessage request = new SendMessage(chatId, text)
.parseMode(ParseMode.HTML)
.disableWebPagePreview(true)
.disableNotification(true)
.replyToMessageId(1)
.replyMarkup(new ForceReply());
// sync
SendResponse sendResponse = bot.execute(request);
boolean ok = sendResponse.isOk();
Message message = sendResponse.message();
System.out.println(ok);
System.out.println(message);
Response is false and null.
I'm referring https://github.com/pengrad/java-telegram-bot-api#send-message
Help me understand the mistake. Thanks.
You need 109780439:AAJqs_w-4 format token, for instance:
TelegramBot bot = new TelegramBot("109780439:AAJqs_w-4");
This token can be obtained from #BotFather.

How to send verification code back to my application from Parse Cloud after success?

So I'm building a signup procedure that needs the user to verify their phone number by receiving a code by sms. I'm using Parse as the backend system and I'm using Twilio service which comes included in Parse to take care of the sms function. I have been successful in sending the verification code to user's number.
This is my parse cloud code:
var client = require('twilio')('ACb3....', '2b3....');
//Send an SMS text message
Parse.Cloud.define("sendVerificationCode", function(request, response) {
var verificationCode = Math.floor(Math.random()*999999);
client.sendSms({
From: "+61437877758",
To: request.params.phoneNumber,
Body: "Your verification code is " + verificationCode + "."
}, function(err, responseData) {
if (err) {
response.error(err);
} else {
response.success("Success");
}
});
});
This is the code from the app:
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("phoneNumber", userNumber);
ParseCloud.callFunctionInBackground("sendVerificationCode", params, new FunctionCallback<String>() {
public void done(String result, ParseException e) {
if (e == null) {
Log.d("Parse", result);
Intent i = new Intent(SignupActivity.this, PhoneVerificationActivity.class);
startActivity(i);
} else {
Toast.makeText(SignupActivity.this, "there was a problem with connection", Toast.LENGTH_LONG).show();
}
}
});
Now I would like to know how can I send that verification code back to my android app from Parse Cloud after success, so tat I can check the verification code against the code user puts in the EditText
if (err) {
response.error(err);
} else {
*//So the code for sending the verification code back goes here:*
response.success("Success");
}
Do I need to use Json and Rest API?, how can I call and grab this verification code from the app?.
I would really appreciate your help. Thanks.
One way would be to return it in response.success...
response.success({ status: "success", verificationCode: ... });
Another way, a better way, is to not trust the client with this. Store a record of it on an object on the server... When the user enters the validation code, call back into another function to check if it is valid. An example of this type of system can be seen in this old out-dated GitHub login example: https://github.com/ParsePlatform/CloudCodeOAuthGitHubTutorial/blob/master/cloud/main.js#L116

Categories