All Projects → Azure → azure-notificationhubs-java-backend

Azure / azure-notificationhubs-java-backend

Licence: Apache-2.0 License
Azure Notification Hubs SDK for Java

Programming Languages

java
68154 projects - #9 most used programming language

Projects that are alternatives of or similar to azure-notificationhubs-java-backend

Django Push Notifications
Send push notifications to mobile devices through GCM or APNS in Django.
Stars: ✭ 1,881 (+5967.74%)
Mutual labels:  push-notifications, apns, gcm, fcm, wns
Node Pushnotifications
Push notifications for GCM, APNS, MPNS, AMZ (automatic detection from device token)
Stars: ✭ 432 (+1293.55%)
Mutual labels:  push-notifications, apns, gcm, fcm
OneSignal-Ionic-Sample
No description or website provided.
Stars: ✭ 85 (+174.19%)
Mutual labels:  push-notifications, apns, gcm, fcm
Pushnotification
PHP and Laravel Package to send push notifications to Android and IOS devices.
Stars: ✭ 395 (+1174.19%)
Mutual labels:  push-notifications, apns, gcm, fcm
Onesignal Ionic Example
Stars: ✭ 89 (+187.1%)
Mutual labels:  push-notifications, apns, gcm, fcm
Onesignal Cordova Sdk
OneSignal is a free push notification service for mobile apps. This plugin makes it easy to integrate your Ionic, PhoneGap CLI, PhoneGap Build, Cordova, or Sencha Touch app with OneSignal. Supports Android, iOS, and Amazon's Fire OS platforms. https://onesignal.com
Stars: ✭ 214 (+590.32%)
Mutual labels:  push-notifications, apns, gcm, fcm
Uniqush Push
Uniqush is a free and open source software system which provides a unified push service for server side notification to apps on mobile devices.
Stars: ✭ 1,238 (+3893.55%)
Mutual labels:  push-notifications, apns, gcm, fcm
Aerogear Unifiedpush Server
🚀 AeroGear UnifiedPush Server
Stars: ✭ 432 (+1293.55%)
Mutual labels:  push-notifications, apns, fcm
Rpush
The push notification service for Ruby.
Stars: ✭ 1,886 (+5983.87%)
Mutual labels:  apns, fcm, wns
Onesignal Android Sdk
OneSignal is a free push notification service for mobile apps. This plugin makes it easy to integrate your native Android or Amazon app with OneSignal. https://onesignal.com
Stars: ✭ 503 (+1522.58%)
Mutual labels:  push-notifications, gcm, fcm
epns
📱 Erlang Push Notifications. APNS(Apple Push Notifications) and FCM(Firebase Cloud Messaging) Push Notifications
Stars: ✭ 13 (-58.06%)
Mutual labels:  apns, gcm, fcm
MongoosePush
MongoosePush is a simple Elixir RESTful service allowing to send push notification via FCM and/or APNS.
Stars: ✭ 101 (+225.81%)
Mutual labels:  apns, gcm, fcm
Gaurun
General push notification server in Go
Stars: ✭ 804 (+2493.55%)
Mutual labels:  push-notifications, apns, gcm
mod push appserver
Simple and extendable appserver for XMPP pushes (aka. XEP-0357)
Stars: ✭ 24 (-22.58%)
Mutual labels:  push-notifications, apns, fcm
andpush
Android Push Notification in Ruby: The fastest client for FCM (Firebase Cloud Messaging)
Stars: ✭ 83 (+167.74%)
Mutual labels:  push-notifications, gcm, fcm
Net Core Push Notifications
Lightweight .NET Core Push Notifications for Android and iOS
Stars: ✭ 105 (+238.71%)
Mutual labels:  push-notifications, apns, fcm
Notificationpusher
Standalone PHP library for easy devices notifications push.
Stars: ✭ 1,143 (+3587.1%)
Mutual labels:  push-notifications, apns, gcm
PUSHTestFCM
[FireMonkey] Push test project
Stars: ✭ 17 (-45.16%)
Mutual labels:  apns, gcm, fcm
Onesignal Unity Sdk
OneSignal is a free push notification service for mobile apps. This plugin makes it easy to integrate your Unity app with OneSignal. https://onesignal.com
Stars: ✭ 161 (+419.35%)
Mutual labels:  push-notifications, apns, gcm
aioapns
An efficient APNs Client Library for Python/asyncio
Stars: ✭ 60 (+93.55%)
Mutual labels:  push-notifications, apns

Maven Central

Microsoft Azure Notification Hubs Java SDK

This repository contains source code for the Java SDK for Microsoft Azure Notification Hubs.

Note on FCM and GCM Support

The Azure Notification Hubs SDK has support for Firebase Cloud Messaging (FCM) via the Legacy HTTP API which is compatible with GCM. For registrations, use the FirebaseRegistration to create registrations, as the GcmRegistration class has been deprecated. For more information, read the Azure Notification Hubs and Google Firebase Cloud Messaging migration

For installations, use the NotificationPlatform.Gcm for all FCM registrations which use the legacy HTTP API. Currently, we do not have full support for FCM and calling NotificationPlatform.Fcm will result in an exception.

Installation i = new Installation();

// Uses the FCM Legacy API
i.setPlatform(NotificationPlatform.Gcm);

Alternatively, we have created installations specific to each platform, for example, the FcmInstallation exists so you do not need to set the NotificationPlatform type.

FcmInstallation i = new FcmInstallation();
i.getPlatform(); // Set to NotificationPlatform.Gcm

Building the Azure Notification Hubs Java SDK

To build, use Maven:

cd NotificationHubs
mvn source:jar javadoc:jar package

Getting Started

To get started, you can find all the classes in the com.windowsazure.messaging package, for example:

import com.windowsazure.messaging.NotificationHub;

The Azure Notification Hubs SDK for Java support both synchronous and asynchronous operations on NotificationHub/NotificationHubClient and NamespaceManager/NamespaceManagerClient. The asynchronous APIs are supported using the org.apache.http.concurrent.FutureCallback interface.

// Synchronous
NotificationHubDescription hub = new NotificationHubDescription("hubname");
hub.setWindowsCredential(new WindowsCredential("sid","key"));
NotificationHubDescription hubDescription = namespaceManager.createNotificationHub(hub);

// Asynchronous
NotificationHubDescription hub = new NotificationHubDescription("hubname");
hub.setWindowsCredential(new WindowsCredential("sid","key"));
namespaceManager.createNotificationHubAsync(hub, new FutureCallback<NotificationHubDescription>() {
    @Override
    public void completed(NotificationHubDescription result) {
        // Handle success
    }

    @Override
    public void failed(Exception ex) {
        // Handle failure
    }

    @Override
    public void cancelled() {
        // Operation has been cancelled
    }
});

Throttling and Retrying Operations

By default, the Azure Notification Hubs SDK for Java by default has a retry policy called the BasicRetryPolicy which retries based upon status codes from Azure Notification Hubs. To swap out your own HttpRequestRetryStrategy, you can use the HttpClientManager.setRetryPolicy method before calling any HTTP operation.

HttpClientManager.setRetryPolicy(new DefaultHttpRequestRetryStrategy(3, TimeValue.ofSeconds(3)));

Azure Notification Hubs Management Operations

This section details the usage of the Azure Notification Hubs SDK for Java management operations for CRUD operations on Notification Hubs and Notification Hub Namespaces.

Create a namespace manager

NamespaceManagerClient namespaceManager = new NamespaceManager("connection string");

Create an Azure Notification Hub

NotificationHubDescription hub = new NotificationHubDescription("hubname");
hub.setWindowsCredential(new WindowsCredential("sid","key"));
hub = namespaceManager.createNotificationHub(hub);

Get a Azure Notification Hub

NotificationHubDescription hub = namespaceManager.getNotificationHub("hubname")

Update an Azure Notification Hub

hub.setMpnsCredential(new MpnsCredential("mpnscert", "mpnskey"));
namespaceManager.updateNotificationHub(hub);

Delete an Azure Notification Hub

namespaceManager.deleteNotificationHub("hubname");

Azure Notification Hubs Operations

The NotificationHub class and NotificationHubClient interface is the main entry point for installations/registrations, but also sending push notifications. To create a NotificationHub, you need the connection string from your Access Policy with the desired permissions such as Listen, Manage and Send, and in addition, the hub name to use.

Create an Azure Notification Hub Client:

NotificationHubClient hub = new NotificationHub("connection string", "hubname");

Azure Notification Hubs Installation API

An Installation is an enhanced registration that includes a bag of push related properties. It is the latest and best approach to registering your devices.

The following are some key advantages to using installations:

  • Creating or updating an installation is fully idempotent. So you can retry it without any concerns about duplicate registrations.
  • The installation model supports a special tag format ($InstallationId:{INSTALLATION_ID}) that enables sending a notification directly to the specific device. For example, if the app's code sets an installation ID of joe93developer for this particular device, a developer can target this device when sending a notification to the $InstallationId:{joe93developer} tag. This enables you to target a specific device without having to do any additional coding.
  • Using installations also enables you to do partial registration updates. The partial update of an installation is requested with a PATCH method using the JSON-Patch standard. This is useful when you want to update tags on the registration. You don't have to pull down the entire registration and then resend all the previous tags again.

Using this SDK, you can do these Installation API operations. For example, we can create an installation for an Amazon Kindle Fire.

AdmInstallation installation = new AdmInstallation("installation-id", "adm-push-channel");
hub.createOrUpdateInstallation(installation);

An installation can have multiple tags and multiple templates with its own set of tags and headers.

installation.addTag("foo");
installation.addTemplate("template1", new InstallationTemplate("{\"data\":{\"key1\":\"$(value1)\"}}","tag-for-template1"));
installation.addTemplate("template2", new InstallationTemplate("{\"data\":{\"key2\":\"$(value2)\"}}","tag-for-template2"));
hub.createOrUpdateInstallation(installation);

For advanced scenarios we have partial update capability which allows to modify only particular properties of the installation object. Basically partial update is subset of JSON Patch operations you can run against Installation object.

PartialUpdateOperation addChannel = new PartialUpdateOperation(UpdateOperationType.Add, "/pushChannel", "adm-push-channel2");
PartialUpdateOperation addTag = new PartialUpdateOperation(UpdateOperationType.Add, "/tags", "bar");
PartialUpdateOperation replaceTemplate = new PartialUpdateOperation(UpdateOperationType.Replace, "/templates/template1", new InstallationTemplate("{\"data\":{\"key3\":\"$(value3)\"}}","tag-for-template1")).toJson());
hub.patchInstallation("installation-id", addChannel, addTag, replaceTemplate);

Delete an Installation:

hub.deleteInstallation(installation.getInstallationId());

Keep in mind that CreateOrUpdate, Patch and Delete are eventually consistent with Get. In fact operation just goes to the system queue during the call and will be executed in background. Moreover Get is not designed for main runtime scenario but just for debug and troubleshooting purposes, it is tightly throttled by the service.

Azure Notification Hub Registration API

A registration associates the Platform Notification Service (PNS) handle for a device with tags and possibly a template. The PNS handle could be a ChannelURI, device token, or FCM registration ID. Tags are used to route notifications to the correct set of device handles. Templates are used to implement per-registration transformation. The Registration API handles requests for these operations.

Create a Windows Registration

WindowsRegistration reg = new WindowsRegistration(new URI(CHANNELURI));
reg.addTag("platform_uwp");
reg.addTag("os_windows10");
WindowsRegistration created = hub.createRegistrationAsync(reg);

Create an Apple Registration

AppleRegistration reg = new AppleRegistration(DEVICETOKEN);
reg.addTag("platform_ios");
reg.addTag("os_tvos");
AppleRegistration created = hub.createRegistrationAsync(reg);

Analogous for Android (GCM), Windows Phone (MPNS), and Kindle Fire (ADM).

Create Template Registrations

WindowsTemplateRegistration reg = new WindowsTemplateRegistration(new URI(CHANNELURI), WNSBODYTEMPLATE);
reg.addHeader("X-WNS-Type", "wns/toast");
WindowsTemplateRegistration created = hub.createRegistration(reg);

Create registrations using create registrationid+upsert pattern (removes duplicates deriving from lost responses if registration ids are stored on the device):

String id = hub.createRegistrationId();
WindowsRegistration reg = new WindowsRegistration(id, new URI(CHANNELURI));
WindowsRegistration upserted = hub.upsertRegistration(reg);

Update a Registration

hub.updateRegistration(reg);

Delete a Registration

hub.deleteRegistration(regid);

Get a Single Registration

Registration registration = hub.getRegistration(regid);

All collection queries support $top and continuation tokens.

Get All Registrations in an Azure Notification Hub

CollectionResult registrations = hub.getRegistrations();

Get Registrations With a Given Tag

CollectionResult registrations = hub.getRegistrationsByTag("platform_ios");

Get Registrations By Channel

CollectionResult registrations = hub.getRegistrationsByChannel("devicetoken");

Send Notifications

The Notification object is simply a body with headers, some utility methods help in building the native and template notifications objects.

Send Windows Native Notification

Notification n = Notification.createWindowsNotification("WNS body");

// broadcast
NotificationOutcome outcome = hub.sendNotification(n);

Set<String> tags = new HashSet<String>();
tags.add("platform_ios");
tags.add("platform_android");
hub.sendNotification(n, tags);

// send to tag expression
NotificationOutcome outcome = hub.sendNotification(n, "platform_ios && ! platform_android");

Send an Apple Push Notification

AppleNotification n = Notification.createAppleNotifiation("APNS body");
NotificationOutcome outcome = hub.sendNotification(n);

Analogous for Android, Windows Phone, Kindle Fire and Baidu PNS.

Send a Template Notification

Map<String, String> props =  new HashMap<String, String>();
props.put("prop1", "v1");
props.put("prop2", "v2");
TemplateNotification n = Notification.createTemplateNotification(props);

NotificationOutcome outcome = hub.sendNotification);

Send To An Installation ID

Send flow for Installations is the same as for Registrations. We've just introduced an option to target notification to the particular Installation - just use tag "$InstallationId:{desired-id}". For case above it would look like this:

WindowsNotification n = Notification.createWindowsNotification("WNS body");
NotificationOutcome outcome = hub.sendNotification(n, "$InstallationId:{installation-id}");

Send to a User ID

With the Installation API we now have a new feature that allows you to associate a user ID with an installation and then be able to target it with a send to all devices for that user. To set the user ID for the installation, set the UserId property of the Installation.

Installation installation = new Installation();
installation.setUserId("user1234");

hub.createOrUpdateInstallation(installation);

The user can then be targeted to send a notification with the tag format of $UserId:{USER_ID}, for example like the following:

String jsonPayload = "{\"aps\":{\"alert\":\"Notification Hub test notification\"}}";
Set<String> tags = new HashSet<String>();
tags.add("$UserId:user1234");

AppleNotification n = Notification.createAppleNotification(jsonPayload);
NotificationOutcome outcome = hub.sendNotification(n, tags);

Send To An Installation Template For An Installation

Map<String, String> props =  new HashMap<String, String>();
props.put("value3", "some value");
TemplateNotification n = Notification.createTemplateNotification(prop);
NotificationOutcome outcome = hub.sendNotification(n, "$InstallationId:{installation-id} && tag-for-template1");

Scheduled Send Operations

Note: This feature is only available for STANDARD Tier.

Scheduled send operations are similar to a normal send operations, with a scheduledTime parameter which says when notification should be delivered. The Azure Notification Hubs Service accepts any point of time between now + 5 minutes and now + 7 days.

Schedule Windows Native Send Operation

Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 1);

Notification n = Notification.createWindowsNotification("WNS body");

NotificationOutcome outcome = hub.scheduleNotification(n, c.getTime())

Import and Export Registrations

Note: This feature is only available for STANDARD Tier.

Sometimes it is required to perform bulk operation against registrations. Usually it is for integration with another system or just to update the tags. It is strongly not recomended to use Get/Update flow if you are modifying thousands of registrations. Import/Export capability is designed to cover the scenario. You provide an access to some blob container under your storage account as a source of incoming data and location for output.

Submit an Export Job

NotificationHubJob job = new NotificationHubJob();
job.setJobType(NotificationHubJobType.ExportRegistrations);
job.setOutputContainerUri("container uri with SAS signature");
job = hub.submitNotificationHubJob(job);

Submit an Import Job

NotificationHubJob job = new NotificationHubJob();
job.setJobType(NotificationHubJobType.ImportCreateRegistrations);
job.setImportFileUri("input file uri with SAS signature");
job.setOutputContainerUri("container uri with SAS signature");
job = hub.submitNotificationHubJob(job)

Wait for Job Completion

while(true) {
    Thread.sleep(1000);
    job = hub.getNotificationHubJob(job.getJobId());
    if(job.getJobStatus() == NotificationHubJobStatus.Completed) {
        break;
    }
}

Get All jobs

List<NotificationHubJobs> allJobs = hub.getAllNotificationHubJobs()

References

Microsoft Azure Notification Hubs Docs

Contributing

For details on contributing to this repository, see the contributing guide.

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, view Microsoft's CLA.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repositories using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Reporting security issues and security bugs

Security issues and bugs should be reported privately, via email, to the Microsoft Security Response Center (MSRC) [email protected]. You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Further information, including the MSRC PGP key, can be found in the Security TechCenter.

License

Azure SDK for Java is licensed under the Apache 2.0 license.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].